简体   繁体   English

使用XElement中的XPath读取包含文本和节点的子节点? LinQ中

[英]Read Child nodes including text and node using XPath from XElement ? LinQ

Using old way of doing via XmlDocument, 使用通过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>";

what is the equivalent of doing the above execution in LinQ when you have XElement variable. 当您拥有XElement变量时,相当于在LinQ中执行上述执行。 I see XPathSelectElement method in XElement but it doesn't return the child nodes + Child nodes text. 我在XElement中看到XPathSelectElement方法,但它不返回子节点+子节点文本。 Any Ideas? 有任何想法吗?

I wouldn't use XPath at all for this. 我根本不会使用XPath。 I'd use: 我用的是:

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

That give the profile nodes and all their descendants. 这给了profile节点及其所有后代。 It's not really clear what you're trying to do with the results, but if you can give more details I should be able to come up with the appropriate code. 你要对结果做什么并不是很清楚,但是如果你能提供更多细节,我应该能够提出适当的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM