空的时候缺少XML节点

时间:2014-04-02 11:44:26

标签: c# xml xpath nodes

我的查询结果为XMLDocument

我想为每个条目提取<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什么?

2 个答案:

答案 0 :(得分:5)

如果没有Notes元素,null,空字符串,您想要哪个值?

我会选择带有Row的{​​{1}}元素,然后检查SelectNodes子元素是否存在并指定null(如下所示)或空字符串(如果不存在):

Notes

答案 1 :(得分: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.