2012-08-14 74 views
2

我在XmlDocument中有以下xml。我试图从中提取className如何从xml检索属性

<Registration className="Eng" type="DirectRegistration" state="Activated"  xmlns="http://xyz/Registration"> 
    <Fields> 
    <Field type="abc" value="123456" /> 
    <Field type="xyz" value="789" /> 
    </Fields> 
</Registration> 

我试过下面的代码,但它没有给我className

var xmlNode = xmlDoc.DocumentElement; 

任何人都可以帮助我得到className的价值。

非常感谢

+0

你尝试过这么远吗?这可能是许多问题中讨论过的最常见的请求之一。 – walther 2012-08-14 10:42:49

回答

4

你几乎有:

var className = xmlDoc.DocumentElement.GetAttribute("className"); 

xmlDoc.DocumentElement给你整个元素; GetAttribute从中提取个人命名属性。

+0

真的很好的答案! – 2012-08-14 10:47:59

1

尝试使用这样的:

// Trying to parse the given file path to an XML 
XmlReader firstXML = XmlReader.Create(XMLPath); 
firstXML.ReadToFollowing("Registration"); 
firstXML.MoveToAttribute("className"); 
var res = firstXML.Value; 

res将举办 “类名” 的值。

1

,您还可以使用XPath来检索属性

string className = xmlDocument.SelectSingleNode("//Registration/@className").Value;