2010-05-12 27 views
0

所以我有以下簡單的XML文件內容的XML文件:.Net,XML和Regex - 如何匹配特定的收集項目?

<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> 

我試圖寫在.net正則表達式相匹配任何CollectionItem其中SubElement2是空的(在這個例子中,中間CollectionItem)。

我有以下的正則表達式到目前爲止(啓用SINGLELINE模式):

<CollectionItem>.+?<SubElement2 />.+?</CollectionItem> 

的問題是,它是匹配所述第一CollectionItem通過第二CollectionItem的接近開口。我明白爲什麼會這樣做,但我不知道如何修改正則表達式以使其僅匹配中心CollectionItem。

編輯:至於爲什麼正則表達式,而不是別的東西:

  1. 我試圖修改該文件中的簡單文本編輯器。
  2. 在我無法弄清楚如何在正則表達式中完成它之後,我想知道是否可以爲了學習而完成(以及如何)。

謝謝!

+0

你的xml在這個例子中是不好的。 SubElement2和SubElement3都有SubElement1結束標記 – Greg 2010-05-12 19:21:09

+0

糟糕,你是對的。現在已經修復了。 – 2010-05-12 19:26:38

回答

2

你可以使用

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

這將確保沒有進一步<CollectionItem>而來的開始標記和<SubElement2 />標籤之間。

+0

多數民衆贊成在工作!謝謝。 – 2010-05-12 20:32:56

5

你爲什麼要使用正則表達式?你有一個完美的域模型(XML) - 爲什麼不搜索它呢?因此,例如在LINQ to XML:

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

var collectionsWithEmptySubElement2 = 
     document.Descendants("CollectionItem") 
       .Where(x => x.Descendants("SubElement2").Any(sub => sub.IsEmpty)); 
+0

我曾經考慮過使用LINQPad來完成這個任務(我試圖用一些無效值修復一個xml數據文件),但是後來我只是很好奇,如果你願意,你會如何在RegEx中實現它。 – 2010-05-12 19:17:38

3

這是XML - 爲什麼你想用正則表達式來做到這一點? XPath不會更有意義嗎?

+0

'/ CollectionItems/CollectionItem [./*/ SubElement2 ='']' – Greg 2010-05-12 19:19:06

相關問題