【问题标题】:Getting attribute value of an XML Document using C#使用 C# 获取 XML 文档的属性值
【发布时间】:2010-09-20 10:49:49
【问题描述】:

假设我有以下 XML 文档。

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

如何获取属性success的值,在本例中为字符串“true”。

【问题讨论】:

  • 解决方案是否必须使用XmlDocument 或任何其他特定的 XML 处理 API?
  • @Daniel:在你去之前:stackoverflow.com/questions/1732348/… ;-)
  • @Isak:我无意走 RegEx 路线!问题谈到了建议使用 DOM API(即XmlDocument)的“XML 文档”,但我问的是是否需要这样做,或者是否可以接受基于流/SAX 的 API,例如 XmlReader。

标签: c# xml


【解决方案1】:

我会尝试这样的:

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

XmlElement root = doc.DocumentElement;

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

【讨论】:

  • 您也可以尝试按名称获取属性:root.Attributes["succes"].Value
  • 按位置访问属性通常是非常糟糕的做法,因为根据定义,XML 元素上的属性顺序并不重要。在这种微不足道的情况下,它可以工作,因为只有一个属性,但这只是幸运。
  • 你说得对,我已经在第一条评论中提出了替代方案。我现在已经编辑了我的原始帖子以显示它。
  • 在我的例子中,我无法像数组一样索引属性,所以我做了如下操作来获取特定属性的值:string s = root.Attributes.GetNamedItem("success").InnerText;
【解决方案2】:

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

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

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

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

如果您使用XPathDocument 或XmlReader 或XDocument,也有类似的方法。

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

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

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

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

【讨论】:

  • 但是我们在这里专门讨论 C#/.NET 并且在 MS 文档中没有提到 XmlReader 或 XmlDocument 索引除文档/输入顺序以外的任何属性,所以如果要求是要“获取出现在输入 XML 中的第一个属性”,这可以通过查找索引为零的属性来实现。当然,问题不是要求“第一个”属性,因此在这种情况下使用属性名称而不是索引是正确的。
  • MS 文档中不能保证XmlDocument(实际上是XmlNamedNodeMap)以任何确定的顺序索引属性。有一些示例显示节点按照它们添加到地图的顺序进行索引。但是这些例子都在这个页面上 - msdn.microsoft.com/en-us/library/7sf9z378.aspx - 祈祷,标题中的第一个单词是什么?
【解决方案3】:
    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();
        }
    }

【讨论】:

  • 查看我对 Rewinder 回答的评论;这个答案有完全相同的问题。它适用于这种微不足道的情况,但通常是一种非常糟糕的做法。
  • 是的,你是对的。我编辑了代码,使其在 XML sn-p 中查找并打印所有“成功”属性值的值,而不管它们的顺序或位置如何。现在把我的零还给我:)
【解决方案4】:
var at = 
XElement.Parse("<reply success=\"true\">More nodes go  </reply>").Attribute("success");
if (at != null) Console.Write(at.Value);

【讨论】:

    【解决方案5】:

    以下代码对我有用。

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

    【讨论】:

      【解决方案6】:

      如果属性值返回 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";      
      

      【讨论】:

        【解决方案7】:

        这是使用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);
        }
        

        【讨论】:

        • 哇,连续三个答案都以三种不同的方式做同样的错误。
        • 我认为最初的问题给人的总体印象是我们应该找到第一个属性的值。我现在已经更正了我的代码,以执行您建议的更普遍有用的事情。
        • @Robert:很公平,答案变了
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-07
        • 2021-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-21
        • 1970-01-01
        相关资源
        最近更新 更多