简体   繁体   中英

Extracting values from an XML file

I have a XML file that's in the following form,

<Mapping name="abc">
  <Attribute name="a1" value="a2" />
  <Attribute name="..." value="..." />
</Mapping>

I want to extract all pairs of Attribute names and values where the Mapping name is "abc" (it occurs in multiple parts of the file). How can I do this?

A XDocument and a XPath expression seems like a very easy way to achieve this:

using System;
using System.Xml.Linq;
using System.Xml.XPath;

class Program
{
    static void Main()
    {
        var doc = XDocument.Load("test.xml");
        var values = doc.XPathSelectElements("//Mapping[@name='abc']");
        foreach (var item in values)
        {
            foreach (var att in item.Elements("Attribute"))
            {
                var name = att.Attribute("name").Value;
                var value = att.Attribute("value").Value;
                Console.WriteLine("{0}: {1}", name, value);
            }
        }
    }
}

or a XmlReader if the XML document is very large and cannot fit into memory:

using System;
using System.Xml;

class Program
{
    static void Main()
    {
        using (var reader = XmlReader.Create("test.xml"))
        {
            bool reading = false;
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element && reader.Name == "Mapping")
                {
                    var name = reader.GetAttribute("name");
                    reading = name == "abc";
                }

                if (reading && reader.NodeType == XmlNodeType.Element && reader.Name == "Attribute")
                {
                    var name = reader.GetAttribute("name");
                    var value = reader.GetAttribute("value");
                    Console.WriteLine("{0}: {1}", name, value);
                }
            }
        }
    }
}

You can use LINQ to XML for this.

var items = from item in purchaseOrder.Descendants("Mapping")
            where (string) item.Attribute("name") == "abc"
            select new
            {
                Name = (string) item.Element("name"),
                Value = (string) item.Element("value")
            };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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