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

时间:2012-05-09 11:04:49

标签: c# asp.net xml c#-4.0

我正在使用c#中的XmlElement。我有XmlElementXmlElement的来源将如下所示。

样品:

<data>
    <p>hello all
        <strong>
            <a id="ID1" href="#" name="ZZZ">Name</a>
        </strong>
    </p>
    <a id="ID2" href="#" name="ABC">Address</a>
</data>

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

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

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

1 个答案:

答案 0 :(得分:4)

由于你使用的是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);
}

无论层次结构中的位置如何,都应该为您提供元素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
}
相关问题