[英]How to get InnerText and InnerXml of a Node from XmlDocument?
例如,我有以下xml字符串:
<?xml version="1.0" encoding="utf-8"?>
<data>
<text>How to get <bold>all</bold> this string's content?</text>
</data>
我想在一个对象数组中获得所有这些元素(对于每个对象我都有一个类),而又不失去它们的结构:
[1] (TextClass; where bold = false) How to get
[2] (TextClass; where bold = true) all
[3] (TextClass; where bold = false) this string's content?
我现在所使用的XmlDocument
和XmlNode
类分别是InnerText或InnerXml。
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("example.xml");
foreach (XmlNode child in xmlDoc.DocumentElement.ChildNodes)
{
string chName = child.Name; // text
string text = child.InnerText; // How to get all this string's content?
string xml = child.InnerXml; // How to get <bold>all</bold>this string's content?
}
可能吗?
对于这种工作,我认为使用LINQ to XML更容易。
在您的示例中,可以执行以下操作(取决于您要实现的目标):
XDocument doc = XDocument.Parse(xml);
var textClasses = from n in doc.Descendants("text").DescendantNodes()
where n.NodeType == XmlNodeType.Text
select new { text = ((XText)n).Value, bold = n.Parent?.Name == "bold" };
.net提琴,以便您可以快速查看结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.