获取整个 XML 节点及其字符串中的标记
本文关键字:字符串 XML 节点 获取 | 更新日期: 2023-09-27 18:32:59
给定以下 XML 示例
<aaa>
<bbb id="1">
<ccc att="123"/>
<ccc att="456"/>
<ccc att="789"/>
</bbb>
<bbb id="2">
<ccc att="321"/>
<ccc att="654"/>
<ccc att="987"/>
</bbb>
</aaa>
作为一个名为 xDoc1
的 XmlDocument 对象,由于它的 ID 和 XPath 指令,我设法删除了第一个bbb
节点,将第二个bbb
节点单独保留在aaa
节点中。
但是现在我想在单个字符串中获取这个已删除的节点及其标记,因为该节点的InnerText
值等于
<ccc att="123"/><ccc att="456"/><ccc att="789"/>
但我希望我的字符串等于
<bbb id='1'><ccc att="123"/><ccc att="456"/><ccc att="789"/></bbb>
我该怎么做?必须使用 XmlDocument。
我尝试使用 ParentNode
方法,但随后它包括另一个bbb
节点。
我目前的C#代码:
xDoc1 = new XmlDocument();
xDoc1.Load("file.xml"); // Containing the given example above.
XmlNodeList nodes = xDoc1.SelectSingleNodes("//bbb[@id='1']");
foreach (XmlNode n in nodes)
{
XmlNode parent = n.ParentNode;
parent.RemoveChild(n);
}
// At this point, xDoc1 does not contain the first bbb node (id='1') anymore.
使用 XmlNode 的 OuterXml 属性
xDoc1 = new XmlDocument();
xDoc1.Load("file.xml"); // Containing the given example above.
XmlNodeList nodes = xDoc1.SelectSingleNodes("//bbb[@id='1']");
foreach (XmlNode n in nodes)
{
XmlNode parent = n.ParentNode;
parent.RemoveChild(n);
Console.WriteLine(n.OuterXml);
}
我首先建议不要使用XmlDocument
。它是旧技术,已被XDocument
取代,它为您提供了Linq2Xml和许多在处理属性等时明确的转换优势。
使用 Linq 而不是 XPath 的 XDocument
方法,解决此问题要容易得多:
var doc=XDocument.Load("file.xml");
var elToRemove = doc.Root.Elements("bbb").Single(el => (int)el.Attribute("id") == 1);
elToRemove.Remove();
Console.WriteLine(doc.ToString()); //no <bbb id="1">
Console.WriteLine(elToRemove.ToString()); //the full outer text of the removed <bbb>