[英]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.