如何使用XMlElement获取元素属性的值

Pat*_*tan 7 c# xml asp.net c#-4.0

我正在研究XmlElement c#.我有一个XmlElement.XmlElement遗嘱的来源如下图所示.

样品:

<data>
    <p>hello all
        <strong>
            <a id="ID1" href="#" name="ZZZ">Name</a>
        </strong>
    </p>
    <a id="ID2" href="#" name="ABC">Address</a>
</data>
Run Code Online (Sandbox Code Playgroud)

我必须循环上面的XML来搜索元素名称a.我还想将该元素的ID提取到变量中.

基本上我想获得元素的ID属性<a>.它可以作为子元素或单独的父元素出现.

任何人都可以帮助完成它.

gid*_*eon 5

由于您使用的是C#4.0,因此可以使用linq-to-xml这样的代码:

XDocument xdoc = XDocument.Load(@"C:\Tmp\your-xml-file.xml");
foreach (var item in xdoc.Descendants("a"))
{
   Console.WriteLine(item.Attribute("id").Value);
}
Run Code Online (Sandbox Code Playgroud)

应该给您元素,a无论它在层次结构中的什么位置。


根据您的评论,对于仅使用XmlDocument和XmlElement类的代码,等效代码为:

XmlDocument dd = new XmlDocument();
dd.Load(@"C:\Tmp\test.xml");
XmlElement theElem = ((XmlElement)dd.GetElementsByTagName("data")[0]);
//         ^^ this is your target element 
foreach (XmlElement item in theElem.GetElementsByTagName("a"))//get the <a>
{
    Console.WriteLine(item.Attributes["id"].Value);//get their attributes
}
Run Code Online (Sandbox Code Playgroud)