如何在XML中获取文本和属性值

XML示例:

   pattern  reg   pattern  reg   

请问,我如何使用System.Xml.Linq获取所有不同节点的不同属性值和文本(例如name,num_brand和enabled for enabled,enabled,type和“reg”for treatment)?

谢谢 !

System.Xml.Linq命名空间比System.Xml命名空间好得多。 您的XDocument有一个XElement ,后者又有子元素。 每个元素都有属性和值。

这是给你的一个例子:

 var text = @"   pattern  reg   <nodepattern>pattern</nodepattern> <attribute type=""text""></attribute> <treatment enabled=""1"" type=""Regex"">reg</treatment>  "; XDocument document = XDocument.Parse(text); // one root element - "brand" System.Diagnostics.Debug.Assert(document.Elements().Count() == 1); XElement brand = document.Element("brand"); // brand has two children - price and title foreach (var element in brand.Elements()) Console.WriteLine("element name: " + element.Name); // brand has three attributes foreach (var attr in brand.Attributes()) Console.WriteLine("attribute name: " + attr.Name + ", value: " + attr.Value); 

你有很多方法可以做到这一点。 其中之一是XmlDocument。

 XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(myXML); foreach(XmlNode node in xmlDoc.DocumentElement.ChildNodes){ string text = node.InnerText; //you can loop through children } 

看一下这篇文章: 如何在C#中读取和解析XML文件?

Personnaly我喜欢Linq To Xml方法,这里有更多信息: https : //msdn.microsoft.com/en-us/library/bb387061.aspx

试试这个

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace ConsoleApplication1 { class Program { const string FILENMAME = @"c:\temp\test.xml"; static void Main(string[] args) { XDocument doc = XDocument.Load(FILENMAME); var brand = doc.Descendants("brand").Select(x => new { name = x.Attribute("name").Value, num_brand = x.Attribute("num_brand").Value, enabled = x.Attribute("enabled").Value, nodePattern = x.Element("price").Element("nodePattern").Value, attribute = x.Element("price").Element("attribute").Attribute("type").Value, priceTreatmentEnable = x.Element("price").Element("treatment").Attribute("enabled").Value, priceTreatmentType = x.Element("price").Element("treatment").Attribute("type").Value, priceTreatment = x.Element("price").Element("treatment").Value, titleTreatmentEnable = x.Element("title").Element("treatment").Attribute("enabled").Value, titleTreatmentType = x.Element("title").Element("treatment").Attribute("type").Value, titleTreatment = x.Element("title").Element("treatment").Value }).FirstOrDefault(); } } }​