2014-04-02 53 views
1

我有一個XMLDocument作爲查詢的結果。XML節點在空時缺失

我想爲每個條目提取<Property>值和適當的<Notes>

<?xml version="1.0"?> 
<EADATA version="1.0" exporter="Enterprise Architect"> 
<Dataset_0> 
    <Data> 
     <Row> 
     <PropertyID>439</PropertyID> 
     <Object_ID>683</Object_ID> 
     <Property>tagged value</Property> 
     <ea_guid>{5BF3E019-277B-45c2-B2DE-1887A90C6944}</ea_guid> 
     </Row> 


     <Row> 
     <PropertyID>444</PropertyID> 
     <Object_ID>683</Object_ID> 
     <Property>Another Tagged value</Property> 
     <Notes>Another tagged value notes.</Notes> 
     <ea_guid>{42BE8BAA-06B8-4822-B79A-59F653C44453}</ea_guid> 
     </Row> 
    </Data> 
    </Dataset_0> 
</EADATA> 

但是,如果<Notes>是空的,沒有<Notes>標籤都沒有。

什麼XPath我應該寫在這種情況下?

+0

這是我不清楚你的願望輸出。所以沒有''元素,所以你想輸出什麼?也許一些預期的輸出爲給定的例子會有所幫助... – dirkk

回答

4
你想要哪個值,如果沒有 Notes元素,空,空字符串

我會選擇元素與SelectNodes然後檢查Notes孩子是否存在,並指定空(如下)或是一個空字符串,如果沒有:

foreach (XmlElement row in doc.SelectNodes("//Row")) 
{ 
    string prop = row.SelectSingleNode("Property").InnerText; 
    string notes = row.SelectSingleNode("Notes") != null ? row.SelectSingleNode("Notes").InnerText : null; 
} 
+0

+1不錯的解決方案。然而,我想知道與我的解決方案有什麼不同。你能詳細說明嗎? (即時通訊談論類的用法,而不是xpath字符串本身) –

+0

@RoyiNamir,我把「XMLDocument」定義爲'System.Xml.XmlDocument',並在.NET框架中使用該DOM API發佈代碼。您在XPathDocument/XPathNavigator和XDocument中使用了不同的API。多年來,.NET框架已經發展到包含用於XML處理的不同API,因此您的解決方案當然也不錯,儘管我不會同時使用XPathDocument和XDocument,但我會單獨使用XPathDocument或XDocument,將它們混合不會似乎有必要。 –

+0

@MartinHonnen是的,但是如何在我的foreach(NodeIter中的XPathNavigator selectedNode)中「消化」'selectedNode''?我嘗試訪問它裏面的屬性,但沒有成功......(這就是爲什麼我添加了XDocument) –

1

試試這個:

XPathDocument docNav = new XPathDocument(new StringReader(xml)); 
XPathNavigator navigator = docNav.CreateNavigator(); 
XPathNodeIterator NodeIter = navigator.Select("/EADATA/Dataset_0/Data/Row"); 

foreach (XPathNavigator selectedNode in NodeIter) 
{ 
    var a= "<root>" + selectedNode.InnerXml + "</root>"; 
    var x= XDocument.Parse(a); 
    Console.WriteLine (x.Root.Element("Property").Value); 
    if (x.Root.Element("Notes")!=null) 
    Console.WriteLine (x.Root.Element("Notes").Value); 

} 

結果:

tagged value 
Another Tagged value 
Another tagged value notes.