簡體   English   中英

從 XML 文件中提取值

[英]Extracting values from an XML file

我有一個 XML 文件,格式如下,

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

我想提取Mapping名稱為"abc"的所有Attribute名稱和值對(它出現在文件的多個部分中)。 我怎樣才能做到這一點?

XDocument和 XPath 表達式似乎是實現此目的的一種非常簡單的方法:

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);
            }
        }
    }
}

如果 XML 文檔非常大並且無法放入 memory,則為XmlReader

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);
                }
            }
        }
    }
}

為此,您可以使用 LINQ 到 XML。

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")
            };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM