XML 节点为空时丢失

本文关键字:节点 XML | 更新日期: 2023-09-27 17:56:23

我有一个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

XML 节点为空时丢失

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

我会选择带有 SelectNodesRow元素,然后检查是否存在Notes子元素并分配 null(如下所述)或空字符串(如果不存在):

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

试试这个:

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.