给出以下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对象,我设法删除了第一个bbb
节点,这要归功于它的ID和XPath指令,而第二个bbb
节点只留在{{1}中一个。
但是现在我希望将此删除的节点及其标记放在一个字符串中,因为此节点的aaa
值等于
InnerText
但我希望我的字符串等于
<ccc att="123"/><ccc att="456"/><ccc att="789"/>
我该怎么办?使用XmlDocument是必需的。
我尝试使用<bbb id='1'><ccc att="123"/><ccc att="456"/><ccc att="789"/></bbb>
方法,但之后它包含了另一个ParentNode
节点。
目前我的C#代码:
bbb
答案 0 :(得分:4)
使用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);
}
答案 1 :(得分:1)
我首先建议不要使用XmlDocument
。它是旧技术和has been superseded by 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>