在C#中从XML获取特定值

时间:2018-10-01 19:12:12

标签: c# xml

<result>
    <resourceName>customEntityEntry</resourceName>
    <size>8</size>
    <entries>
        <entry id="32537965" 
               link="/customEntity/88336/customEntityEntry/32537965.xml"/>
        <entry id="32537966" 
               link="/customEntity/88336/customEntityEntry/32537966.xml"/>
        <entry id="32537967" 
               link="/customEntity/88336/customEntityEntry/32537967.xml"/>
        <entry id="32537972" 
               link="/customEntity/88336/customEntityEntry/32537972.xml"/>
        <entry id="32537975" 
               link="/customEntity/88336/customEntityEntry/32537975.xml"/>
        <entry id="32537978" 
               link="/customEntity/88336/customEntityEntry/32537978.xml"/>
        <entry id="32537979" 
               link="/customEntity/88336/customEntityEntry/32537979.xml"/>
        <entry id="32537981" 
               link="/customEntity/88336/customEntityEntry/32537981.xml"/>
    </entries>
</result>

我上面有这个XML,对于example/customEntity/88336/customEntityEntry/32537965.xml,只需要获取每个条目的“链接”值即可。这需要动态完成,因为条目数会有所不同。

我尝试使用System.XML和正则表达式,但没有成功。

1 个答案:

答案 0 :(得分:2)

一种简单的方法是使用Linq To XML。即:

string xml = @"<result>
<resourceName>customEntityEntry</resourceName>
<size>8</size>
<entries>
<entry id=""32537965"" 
link=""/customEntity/88336/customEntityEntry/32537965.xml""/>
<entry id=""32537966"" 
link=""/customEntity/88336/customEntityEntry/32537966.xml""/>
<entry id=""32537967"" 
link=""/customEntity/88336/customEntityEntry/32537967.xml""/>
<entry id=""32537972"" 
link=""/customEntity/88336/customEntityEntry/32537972.xml""/>
<entry id=""32537975"" 
link=""/customEntity/88336/customEntityEntry/32537975.xml""/>
<entry id=""32537978"" 
link=""/customEntity/88336/customEntityEntry/32537978.xml""/>
<entry id=""32537979"" 
link=""/customEntity/88336/customEntityEntry/32537979.xml""/>
<entry id=""32537981"" 
link=""/customEntity/88336/customEntityEntry/32537981.xml""/>
</entries>
</result>
";


var links = XElement.Parse(xml)
   .DescendantsAndSelf()
   .Where(xe => xe.Attribute("link") != null)
   .Select(xe => (string)xe.Attribute("link"));