0

假设我有一个这样的 XmlDocument:

<xmlFile>
  <details>
    <code1>ADJ</code1>
    <code2>ADC </code2>
    <Shipment>
      <foo></foo>
      <bar></bar>
    </Shipment>
    <Shipment>
      <foo></foo>
      <bar></bar>
    </Shipment>
  </details>
  <details>
    <code1>ADJ</code1>
    <code2>SCC </code2>
    <Shipment>
      <foo></foo>
      <bar></bar>
    </Shipment>
  </details>
</xmlFile>

我需要在一个 xml 文件中处理每一个,但只处理属于具有值为“ADC”的子节点的标签下的货物。到目前为止,我有:

// Assume there is an XmlDocument named xml 
XmlNodeList details= xml.GetElementsByTagName("details");

foreach (XmlNode node in details)
{
   if (node["code2"].InnerText == "ADC ")
   {
   // Get each shipment and process it accordingly.
   }
}

我不知道下一步该做什么。谢谢。

4

4 回答 4

0

这就是你所追求的东西

        XmlNodeList details = xml.GetElementsByTagName("details");

        foreach (XmlNode node in details)
        {
            if (node["code2"].InnerText.Trim() == "ADC")
            {
                // Get each shipment and process it accordingly.
                foreach(XmlNode shipment in node.SelectNodes("Shipment"))
                {
                    var foo = shipment.SelectSingleNode("foo");
                    var bar = shipment.SelectSingleNode("bar");
                }
            }
        }
于 2012-05-14T15:49:59.470 回答
0

我正在向这个库添加 XPath 解析:https ://github.com/ChuckSavage/XmlLib/

我修改了它,所以你可以这样做:

XElement root = XElement.Load(file);
var shipments = root.XPath("details[starts-with(*,'ADC')]/Shipment");

长手看起来像:

var shipments = root.Elements("details")
                    .Where(x => x.Elements().Any(xx => ((string)xx).StartsWith("ADC")))
                    .Elements("Shipment");
于 2012-05-14T20:43:53.157 回答
0

XPath 可以简化您的匹配搜索:

foreach (XmlNode node in xml.SelectNodes("/xmlFile/details[normalize-space(code2)='ADC']"))
{
    string foo = node.SelectSingleNode("foo").InnerText;
    string bar = node.SelectSingleNode("bar").InnerText;
}
于 2012-05-14T16:04:55.470 回答
0

假设 Data\Sample.xml 包含问题中提到的 xml,
以下是 XLINQ 查询

    XElement root = XElement.Parse(File.ReadAllText(@"Data\Sample.xml"));
    var adcShipment = root.Descendants().Where(e=>String.Equals(e.Value, "ADC "));
    //next query for nodes/elements inside/next to ADC shipments
于 2012-05-14T15:40:13.330 回答