[英]Getting attribute value of an XML Document using C#
假设我有以下XML文档。
<reply success="true">More nodes go here</reply>
如何获取属性成功的值,在这种情况下将是字符串“true”。
我会尝试这样的事情:
XmlDocument doc = new XmlDocument();
doc.LoadXml("<reply success=\"true\">More nodes go here</reply>");
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"));
如果您使用XPathDocument
或XmlReader
或XDocument
则有类似的方法。
但是,在所有情况下,您希望按名称获取属性,而不是其位置。 在您的测试用例中,只有一个属性; 在任何现实世界的应用程序中,可能存在多个属性,并且XML中的属性排序并不重要。 这两个元素在语义上是等价的:
<a foo='true' bar='false'/>
<a bar='false' foo='true'/>
您甚至不知道XML解析器将按照它们在文档中出现的顺序向您显示属性; 根据实现,解析器可能按字母顺序或随机顺序将它们提供给您。 (我见过两个。)
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);
以下代码适用于我。
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);
}
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";
这是使用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.