【问题标题】:get specific xelement child value获取特定的 xelement 子值
【发布时间】:2016-11-28 12:05:04
【问题描述】:
<information items ="2">
    <table id="31"> </table>
    <profile code="5">
        <name language="ro"> Spania </name>
        <name language="gb"> Spain </name>
        <name language="pl"> Hiszpania </name>
    </profile>
</information>

我确实想获取具有属性language = "gb" 的元素&lt;name&gt; 的值

我尝试了类似的方法:

string country = xdoc.Descendants("information").Elements("profile").Elements("name")./*???Value???*?

我怎样才能做到这一点?

【问题讨论】:

    标签: c# .net xml xpath


    【解决方案1】:

    你可以使用XPath

    System.Xml.Linq.XDocument:

    string country = xdoc.XPathSelectElement("/information/profile/name[@language='gb']").Value;
    

    System.Xml.XmlDocument:

    string country = xdoc.SelectSingleNode("/information/profile/name[@language='gb']").InnerText;
    

    请记住,您还需要 System.Xml.XPath 命名空间。

    【讨论】:

    • 我有:XDocument xdoc = XDocument.Load(reader);和 reader = XmlReader.Create(Url); reader.MoveToContent();
    • 然后使用第一个示例。它用于System.Xml.Linq 命名空间
    • 对于第二个示例,xdoc 应该是 XmlNode,而不是 XDocument?
    • 但在我的场景中:xdoc 是 XDocument,而不是 XmlNode
    • 我添加了这个:使用 System.Xml.XPath;现在它可以工作了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多