【问题标题】:Read Child nodes including text and node using XPath from XElement ? LinQ使用 XElement 中的 XPath 读取子节点,包括文本和节点?林奇
【发布时间】:2011-10-31 08:12:09
【问题描述】:

使用通过 XmlDocument 的旧方式,

string xmlstring = "<root><profile><Name>John</Name><Age>23</Age></profile></root>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlstring);
string childNodes = xmlDoc.SelectSingleNode("root/Profile").InnerXml;

// output of childNodes would be => "<Name>John</Name><Age>23</Age>";

当您有 XElement 变量时,在 LinQ 中执行上述执行的等价物是什么。我在 XElement 中看到 XPathSelectElement 方法,但它不返回子节点 + 子节点文本。有什么想法吗?

【问题讨论】:

  • 为什么要获取InnerXml?之后你想用它做什么?

标签: c# xml linq linq-to-xml


【解决方案1】:

我根本不会为此使用 XPath。我会使用:

XDocument doc = XDocument.Parse(xmlString);
var nodes = doc.Root
               .Elements("profile")
               .DescendantsAndSelf();

这给出了profile 节点及其所有后代。目前尚不清楚您要对结果做什么,但如果您能提供更多详细信息,我应该能够提出适当的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    相关资源
    最近更新 更多