SelectNodes返回许多结果



加载此XML工作

<?xml version="1.0" encoding="utf-8" ?>
<export>
<document ID="uuuid_1">
<Property Name="PersonName" Value="bob"></Property>
<Property Name="FileName" Value="bob.tif">
<Reference Link="companyexportuuuid_1_423_bob.tif"/>              
</Property>
<Property Name="FileName" Value="bob.txt">
<Reference Link="companyexportuuuid_1_123_bob.txt"/>
</Property>
<Property Name="FileName" Value="bob.tif">
<Reference Link="companyexportuuuid_1_123_bob.tif"/>
</Property>
</document>
<document ID="uuuid_2">
<Property Name="PersonName" Value="mary"></Property>
<Property Name="FileName" Value="mary.tif">
<Reference Link="companyexportuuuid_2_456_mary.tif"/>
</Property>
<Property Name="FileName" Value="mary.txt">
<Reference Link="companyexportuuuid_2_567_mary.txt"/>
</Property>
</document>
</export>

用这种方法

static void XmlLoader(string xml_path)
{
Console.WriteLine("Loading " + xml_path);
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(xml_path);
XmlNodeList nodes_document = xmldoc.SelectNodes("/export/document");
foreach (XmlNode nd in nodes_document)
{
string Id = nd.Attributes["ID"].Value.ToString();
string name = nd.SelectSingleNode("//Property[@Name='PersonName']/@Value").InnerText;
XmlNodeList files = nd.SelectNodes("//Property[@Name='FileName'][contains(@Value,'.tif')]/Reference/@Link");
Console.WriteLine(files.ToString());
}
}

文档迭代中的XmlNodeList会返回XML中所有tif的列表,而不仅仅是来自nd Node的tif。

如何正确使用Xpath来选择nd元素中的列表?

只需移除"/"从CCD_ 1和CCD_。双斜线正在解析完整的xml

static void XmlLoader(string xml_path)
{
Console.WriteLine("Loading " + xml_path);
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(xml_path);
XmlNodeList nodes_document = xmldoc.SelectNodes("/export/document");
foreach (XmlNode nd in nodes_document)
{
string Id = nd.Attributes["ID"].Value.ToString();
string name = nd.SelectSingleNode("Property[@Name='PersonName']/@Value").InnerText;
XmlNodeList files = nd.SelectNodes("Property[@Name='FileName'][contains(@Value,'.tif')]/Reference/@Link");
Console.WriteLine(files.ToString());
}
}

最新更新