简体   繁体   English

读取 XML 文档并删除节点

[英]Read an XML document and removing nodes

I have an XML file, similar to the one below.我有一个 XML 文件,类似于下面的那个。 I will read the XML and find the EmpId node.我将阅读 XML 并找到 EmpId 节点。 Based on other data will determine if I need to keep this node or delete the node.根据其他数据将确定我是否需要保留此节点或删除该节点。 Currently have a process which reads it and creates a list of Record Ids which I will need to remove.目前有一个进程可以读取它并创建一个我需要删除的记录 ID 列表。 In the below XML I will want to keep the EmpId = Emp1 and remove EmpId = Emp2.在下面的 XML 中,我希望保留 EmpId = Emp1 并删除 EmpId = Emp2。 The removal is the node.移除的是节点。

I believe the best approach is to read the XML first to determine which nodes to keep and then go thru the XML again and remove the necessary nodes.我相信最好的方法是首先读取 XML 以确定要保留哪些节点,然后再次通过 XML 并删除必要的节点。

What's the best approach to remove these nodes?删除这些节点的最佳方法是什么?
I'm open to creating a new XML document and creating the node which need to be kept.我愿意创建一个新的 XML 文档并创建需要保留的节点。 Based on the data I'm reading it's 50/50 if I'll be removing more nodes or keeping more nodes.根据我正在阅读的数据,如果我要删除更多节点或保留更多节点,则为 50/50。

...
<HeaderNode>
  <Details>
    <SubmissionId>1</SubmissionId>
    <EmpDetail>
      <RecordId>1</RecordId>
      <EmpDempgraphic>
        <EmpId>Emp1</EmpId>
      </EmpDempgraphic>
    </EmpDetail>
    <EmpDetail>
      <RecordId>2</RecordId>
      <EmpDempgraphic>
        <EmpId>Emp2</EmpId>
      </EmpDempgraphic>
    </EmpDetail>
  </Details>
</HeaderNode>
...

除非文档很大,否则只需将其加载到XDocument 中删除不需要的元素,然后文档保存回来。

Using Xml Linq :使用 Xml Linq :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace XML
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement EmpDetail = doc.Descendants("EmpDetail").Where(x => (int)x.Element("RecordId") == 2).FirstOrDefault();

            EmpDetail.Remove();

        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM