.Net、XML和;正则表达式-如何匹配特定集合项?

.Net、XML和;正则表达式-如何匹配特定集合项?,.net,xml,regex,.net,Xml,Regex,因此,我有一个xml文件,其中包含以下简化的xml文件内容: <CollectionItems> <CollectionItem> <Element1>Value1</Element1> <Element2> <SubElement1>SubValue1</SubElement1> <SubElement2>Sub

因此,我有一个xml文件,其中包含以下简化的xml文件内容:

<CollectionItems>
    <CollectionItem>
        <Element1>Value1</Element1>
        <Element2>
            <SubElement1>SubValue1</SubElement1>
            <SubElement2>SubValue2</SubElement2>
            <SubElement3>SubValue3</SubElement3>
        </Element2>
        <Element3>Value3</Element3>
    </CollectionItem>
    <CollectionItem>
        <Element1>Value1</Element1>
        <Element2>
            <SubElement1>SubValue1</SubElement1>
            <SubElement2 />
            <SubElement3>SubValue3</SubElement3>
        </Element2>
        <Element3>Value3</Element3>
    </CollectionItem>
    <CollectionItem>
        <Element1>Value1</Element1>
        <Element2>
            <SubElement1>SubValue1</SubElement1>
            <SubElement2>SubValue2</SubElement2>
            <SubElement3>SubValue3</SubElement3>
        </Element2>
        <Element3>Value3</Element3>
    </CollectionItem>
</CollectionItems>

价值1
子值1
子值2
子值3
价值3
价值1
子值1
子值3
价值3
价值1
子值1
子值2
子值3
价值3
我试图在.Net中编写一个正则表达式,它匹配SubElement2为空的任何CollectionItem(本例中的中间CollectionItem)

到目前为止,我有以下正则表达式(已启用单线模式):

+?。+?
问题在于,它通过关闭第二个CollectionItem来匹配第一个CollectionItem的期初。我理解它为什么这样做,但我不知道如何修改正则表达式使其仅与中心集合项匹配

编辑:关于为什么regex与其他东西相反:

  • 为了简单起见,我试图在文本编辑器中修改该文件
  • 在我不知道如何在regex中实现它之后,我想知道为了学习,是否可以(以及如何)实现它

  • 谢谢

    为什么要尝试使用正则表达式?您已经有了一个非常好的域模型(XML)-为什么不搜索它呢?例如,在LINQ to XML中:

    var collectionsWithEmptySubElement2 =
           document.Descendants("SubElement2")
                   .Where(x => x.IsEmpty)
                   .Select(x => x.Ancestors("CollectionItem").FirstOrDefault());
    


    这就是XML——为什么要用正则表达式来实现这一点?XPath不是更有意义吗?

    您可以使用

    <CollectionItem>((?!<CollectionItem>).)+?<SubElement2 />.+?</CollectionItem>
    
    ((?!)+?
    

    这确保了在起始标记和
    标记之间不再出现进一步的
    标记。

    我曾经考虑过使用LINQPad来完成这项工作(我正在尝试修复一个带有一些无效值的xml数据文件),但后来我开始好奇,如果您愿意的话,您将如何在RegEx中真正做到这一点。
    /CollectionItems/CollectionItem[./*/SubElement2=''']
    示例中您的xml不正确。SubElement2和SubElement3都有SubElement1结束标记。如果您是正确的,现在已修复。
    var collectionsWithEmptySubElement2 =
           document.Descendants("CollectionItem")
                   .Where(x => x.Descendants("SubElement2").Any(sub => sub.IsEmpty));
    
    <CollectionItem>((?!<CollectionItem>).)+?<SubElement2 />.+?</CollectionItem>