使用C#获取XML文档的属性值

假设我有以下XML文档。

More nodes go here 

如何获取属性成功的值,在这种情况下将是字符串“true”。

我会尝试这样的事情:

 XmlDocument doc = new XmlDocument(); doc.LoadXml("More nodes go here"); XmlElement root = doc.DocumentElement; string s = root.Attributes["success"].Value; 

如果将XML加载到XmlDocument ,则可以通过多种方式获取属性的值。 您可以使用XPath来查找属性:

 XmlAttribute a = doc.SelectSingleNode("/reply/@success"); Console.Write(a.Value); 

如果您已经拥有该属性出现的XmlElement (在本例中是文档元素),那么您可以使用GetAttribute

 Console.Write(doc.DocumentElement.GetAttribute("success")); 

如果您使用XPathDocumentXmlReaderXDocument则有类似的方法。

但是,在所有情况下,您希望通过名称获取属性,而不是其位置。 在您的测试用例中,只有一个属性; 在任何现实世界的应用程序中,可能存在多个属性,并且XML中的属性排序并不重要。 这两个元素在语义上是等价的:

   

您甚至不知道XML解析器将按照它们在文档中出现的顺序向您显示属性; 根据实现,解析器可以按字母顺序或随机顺序将它们提供给您。 (我见过两者。)

  using System; using System.Linq; using System.Xml.Linq; class MyClass { static void Main(string[] args) { XElement xmlcode = XElement.Parse("More nodes go "); var successAttributes = from attribute in xmlcode.Attributes() where attribute.Name.LocalName=="success" select attribute ; if(successAttributes.Count()>0) foreach (var sa in successAttributes) { Console.WriteLine(sa.Value); } Console.ReadLine(); } } 
 var at = XElement.Parse("More nodes go ").Attribute("success"); if (at != null) Console.Write(at.Value); 

以下代码适用于我。

 String strXML = "More nodes go here"; using (XmlReader reader = XmlReader.Create(new StringReader(strXML))) { reader.ReadToFollowing("reply"); reader.MoveToContent(); string strValue = reader.GetAttribute("success"); Console.WriteLine(strValue); } 

这是使用XmlReader的替代解决方案,它可能比使用XmlDoument更有效,尽管在这样一个小型XML文档上这可以忽略不计

 string input = "More nodes go here"; using (XmlReader xmlReader = XmlReader.Create(new StringReader(input))) { xmlReader.MoveToContent(); string success = xmlReader.GetAttribute("success"); Console.WriteLine(success); }