简体   繁体   English

为节点解析 XML,然后是子节点

[英]Parsing XML for nodes, and then child nodes

My XML looks like this:我的 XML 看起来像这样:

<data>
  <location ....>
      <stores>
         <store ....></store>
         <store ... ></store>
      </stores>
  </location>
</data>

I want to loop through all the location elements, and then loop through all the stores.我想遍历所有位置元素,然后遍历所有商店。

I also want access to the attributes of both location and store elements.我还想访问 location 和 store 元素的属性。

I have loaded the xml document:我已经加载了 xml 文档:

var doc = new XmlDocument();
doc.LoadXml(myXmlAsString);

Let's say this is your sample XML假设这是您的示例XML

<data>
  <location sample="something">
      <stores>
         <store atrb="1">store1</store>
         <store atrb="2">store2</store>
      </stores>
  </location>
  <location>
      <stores>....</stores>
  </location>
</data>

Then using XDocument of System.Xml.Linq , you access all the locations, stores and their attributes like this然后使用System.Xml.Linq XDocument ,您可以像这样访问所有位置、商店及其属性

var xmlString = File.ReadAllText(@"C:\YourDirectory\YourFile.xml");
XDocument geneva = XDocument.Parse(xmlString);

var locations = geneva.Descendants("location");
foreach (var location in locations)
{
    var sampleAttribute = location.Attribute("sample").Value;
    var stores = location.Descendants("store");
    foreach (var store in stores)
    {
        var value = store.Value;
        var atrbValue = store.Attribute("atrb").Value;
    }
}

If you dont want to use XmlSerializer to get the typed data you can get nodes by criteria with SelectSingleNode or SelectNodes methods.如果您不想使用 XmlSerializer 来获取类型化数据,您可以使用 SelectSingleNode 或 SelectNodes 方法按条件获取节点。 This will give you ability to iterate through location elemets.这将使您能够遍历位置元素。 I would suggest creating classes to deserialize to because its easier to work with.我建议创建类来反序列化,因为它更容易使用。

Loop through locations:循环位置:

XmlNodeList xnList = doc.SelectNodes("/data/location");
            foreach(XmlNode node in xnList)
            {
                  //your code goes here..
            }

Loop through all stores:遍历所有商店:

XmlNodeList xnList = doc.SelectNodes("/data/location/stores");
            foreach(XmlNode node in xnList)
            {
                    //your code here..
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM