gpt4 book ai didi

c# - 获取整个 XML 节点及其在字符串中的标记

转载 作者:太空宇宙 更新时间:2023-11-03 19:54:43 25 4
gpt4 key购买 nike

给定以下 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);
}

关于c# - 获取整个 XML 节点及其在字符串中的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35180386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com