【问题标题】:Getting a whole XML node with its markups in a string在字符串中获取带有标记的整个 XML 节点
【发布时间】:2016-02-04 16:06:34
【问题描述】:

给出以下 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.

【问题讨论】:

  • 请将 XML 视为代码,同时缩进四个空格。谢谢。

标签: c# xml xpath


【解决方案1】:

使用 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);
}

【讨论】:

  • 这行得通!当一个单一的财产可以完成这项工作时,我很生气我寻求帮助......非常感谢! :)
【解决方案2】:

我首先建议不要使用XmlDocument。它是旧技术和has been superseded by XDocument,在处理属性等时,它为您提供了 Linq2Xml 和许多显式转换优点。

使用XDocument 方法和 Linq 而不是 XPath,解决这个问题要容易得多:

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>

【讨论】:

  • OP 还希望删除元素中的三个子节点“”......也许你应该更新你的答案以包含它
  • @Viru 我不明白你要我包括什么。被移除元素的后代保持不变(即,当 标记由于是子元素而被移除时,它们被移除)。
  • 问题是 XmlDocument 在项目的其他地方都用到了,我必须继续使用它。对不起,我没有指定它,编辑我的问题。不过谢谢你的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多