简体   繁体   English

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

[英]Getting attribute value of an XML Document using C#

Suppose I have the following XML Document. 假设我有以下XML文档。

<reply success="true">More nodes go here</reply>

How to get the value of the attribute success, which in this case would be the string "true". 如何获取属性成功的值,在这种情况下将是字符串“true”。

I would try something like this: 我会尝试这样的事情:

XmlDocument doc = new XmlDocument();
doc.LoadXml("<reply success=\"true\">More nodes go here</reply>");

XmlElement root = doc.DocumentElement;

string s = root.Attributes["success"].Value;

If you load the XML into an XmlDocument , there are any number of ways to get the attribute's value. 如果将XML加载到XmlDocument ,则可以通过多种方式获取属性的值。 You could use XPath to find the attribute: 您可以使用XPath来查找属性:

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

If you already have the XmlElement that the attribute appears on (which in this case is the document element), then you can just use GetAttribute : 如果您已经拥有该属性出现的XmlElement (在本例中是文档元素),那么您可以使用GetAttribute

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

There are similar approaches if you're using XPathDocument or XmlReader or XDocument . 如果您使用XPathDocumentXmlReaderXDocument则有类似的方法。

In all cases, though, you want to be getting the attribute by its name , not its position. 但是,在所有情况下,您希望按名称获取属性,而不是其位置。 In your test case there's only one attribute; 在您的测试用例中,只有一个属性; in any real-world application multiple attributes are likely, and attribute ordering in XML is not significant. 在任何现实世界的应用程序中,可能存在多个属性,并且XML中的属性排序并不重要。 These two elements are semantically equivalent: 这两个元素在语义上是等价的:

<a foo='true' bar='false'/>

<a bar='false' foo='true'/>

You don't even know that the XML parser will present attributes to you in the same order they appear in the document; 您甚至不知道XML解析器将按照它们在文档中出现的顺序向您显示属性; depending on the implementation, the parser may give them to you in alphabetical order, or in random order. 根据实现,解析器可能按字母顺序或随机顺序将它们提供给您。 (I've seen both.) (我见过两个。)

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

    class MyClass
    {
        static void Main(string[] args)
        {
            XElement xmlcode =
            XElement.Parse("<reply success=\"true\">More nodes go  </reply>");

            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("<reply success=\"true\">More nodes go  </reply>").Attribute("success");
if (at != null) Console.Write(at.Value);

The following code works for me. 以下代码适用于我。

String strXML = "<reply success=\"true\">More nodes go here</reply>";

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

If attribute value returns null or empty, try this. 如果属性值返回null或空,请尝试此操作。

     string x="<node1 id='12345'><node2 Name='John'></node2><node3 name='abc'></node3></node1>";
        XmlDocument xml = new XmlDocument();
        xml.LoadXml(x);
        var node = xml.GetElementsByTagName("node3");
        xml = new XmlDocument();
        xml.LoadXml(nodes[0].OuterXml);
        XmlElement root = xml.DocumentElement;
        String requiredValue = root.GetAttribute("name");  
    returns "abc";      

Here's an alternative solution using XmlReader which may be a little more efficient than using XmlDoument although that's proably negligible on such a small XML document 这是使用XmlReader的替代解决方案,它可能比使用XmlDoument更有效,尽管在这样一个小型XML文档上这个问题可以忽略不计

string input = "<reply success=\"true\">More nodes go here</reply>";

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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