谢谢!解决方案 System.Xml.Linq命名空间比System.Xml命名空间好得多.您的XDocument有一个XElement,而后者又有子元素.每个元素都有属性和一个值.这是给你的例子:var text = @"<?xml version=""1.0"" encoding=""utf-8"" ?> <brand name=""brand1"" num_brand=""118"" enabled=""True""> <price> <nodePattern>pattern</nodePattern> <attribute type=""text"" ></attribute> <treatment enabled=""1"" type=""Regex"">reg</treatment> </price> <title> <nodePattern>pattern</nodePattern> <attribute type=""text"" ></attribute> <treatment enabled=""1"" type=""Regex"">reg</treatment> </title> </brand>";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 titleforeach (var element in brand.Elements()) Console.WriteLine("element name: " + element.Name);// brand has three attributesforeach (var attr in brand.Attributes()) Console.WriteLine("attribute name: " + attr.Name + ", value: " + attr.Value);XML example : <?xml version="1.0" encoding="utf-8" ?><brand name="brand1" num_brand="118" enabled="True"> <price> <nodePattern>pattern</nodePattern> <attribute type="text" ></attribute> <treatment enabled="1" type="Regex">reg</treatment> </price> <title> <nodePattern>pattern</nodePattern> <attribute type="text" ></attribute> <treatment enabled="1" type="Regex">reg</treatment> </title></brand>Please, how can I get the different attributes values and text for all my different nodes (for example name, num_brand and enabled for brand, enabled, type and "reg" for treatment) using System.Xml.Linq ?Thank you ! 解决方案 The System.Xml.Linq namespace is much nicer than the System.Xml namespace. Your XDocument has one XElement, which in turn has children elements. Each element has attributes and a value.Here's an example for you:var text = @"<?xml version=""1.0"" encoding=""utf-8"" ?> <brand name=""brand1"" num_brand=""118"" enabled=""True""> <price> <nodePattern>pattern</nodePattern> <attribute type=""text"" ></attribute> <treatment enabled=""1"" type=""Regex"">reg</treatment> </price> <title> <nodePattern>pattern</nodePattern> <attribute type=""text"" ></attribute> <treatment enabled=""1"" type=""Regex"">reg</treatment> </title> </brand>";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 titleforeach (var element in brand.Elements()) Console.WriteLine("element name: " + element.Name);// brand has three attributesforeach (var attr in brand.Attributes()) Console.WriteLine("attribute name: " + attr.Name + ", value: " + attr.Value); 这篇关于如何在XML中获取文本和属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-10 22:51