使用RemoveChild()删除子节点

发布于 2024-09-09 04:50:29 字数 911 浏览 3 评论 0原文

我想仅删除此一个节点,例如:

此 XML 中的Sample2

,例如:

 <Tests> <Test ID="0" AllowMultipleSelect="1">
  <Name>BaseSamples</Name>
  <Sample ID="546" Type="0">Sample1 </Sample>
  <Sample ID="135" Type="0">Sample45</Sample>
  <Sample ID="544" Type="0">Sample2</Sample>
  <Sample ID="5818" Type="0" >Sample78</Sample>
  </Test>
  </Tests>

这样我的结果如下:

 <Tests> <Test ID="0" AllowMultipleSelect="1">
  <Name>BaseSamples</Name>
  <Sample ID="546" Type="0">Sample1 </Sample>
  <Sample ID="135" Type="0">Sample45</Sample>
  <Sample ID="5818" Type="0" >Sample78</Sample>
  </Test>
  </Tests>

我可以一次删除任何一个节点(因为我放置了一个循环来检查需要删除的示例 ID) 任何帮助将不胜感激,提前致谢。

I would like to delete just this one node, for example:

<Sample ID="544" Type="0">Sample2</Sample>

from this XML, for example:

 <Tests> <Test ID="0" AllowMultipleSelect="1">
  <Name>BaseSamples</Name>
  <Sample ID="546" Type="0">Sample1 </Sample>
  <Sample ID="135" Type="0">Sample45</Sample>
  <Sample ID="544" Type="0">Sample2</Sample>
  <Sample ID="5818" Type="0" >Sample78</Sample>
  </Test>
  </Tests>

so that my results something like this:

 <Tests> <Test ID="0" AllowMultipleSelect="1">
  <Name>BaseSamples</Name>
  <Sample ID="546" Type="0">Sample1 </Sample>
  <Sample ID="135" Type="0">Sample45</Sample>
  <Sample ID="5818" Type="0" >Sample78</Sample>
  </Test>
  </Tests>

I would be okay with deleting any one node at a time (since I put a loop to check for sample IDs that need to be deleted)
Any help would be appreciated, thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我纯我任性 2024-09-16 04:50:29
XmlElement el = (XmlElement)originalXml.SelectSingleNode("/Tests/Test/Sample[@id='544']");
            if (el != null) {
                el.ParentNode.RemoveChild(el);
                originalXml.Save(@"d:\file.xml");
            }
XmlElement el = (XmlElement)originalXml.SelectSingleNode("/Tests/Test/Sample[@id='544']");
            if (el != null) {
                el.ParentNode.RemoveChild(el);
                originalXml.Save(@"d:\file.xml");
            }
面犯桃花 2024-09-16 04:50:29

通过简单的搜索就在网上找到了这个:

XmlNode node = document.SelectSingleNode("/Tests/Test/Sample[@id='544']");
node.ParentNode.RemoveChild(t);
document.Save();

Found this online with a simple search:

XmlNode node = document.SelectSingleNode("/Tests/Test/Sample[@id='544']");
node.ParentNode.RemoveChild(t);
document.Save();
友谊不毕业 2024-09-16 04:50:29

我还没有测试过这段代码,但它应该可以工作。

XmlDocument xDoc = new XmlDocument();
xDoc.Load("file.xml");
xDoc.RemoveChild(xDoc.SelectSingleNode("//Sample[@ID='554']"));

I haven't tested this code but it should work.

XmlDocument xDoc = new XmlDocument();
xDoc.Load("file.xml");
xDoc.RemoveChild(xDoc.SelectSingleNode("//Sample[@ID='554']"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文