【问题标题】:How to remove and add xml particular node using c#?如何使用 c# 删除和添加 xml 特定节点?
【发布时间】:2016-06-28 16:18:39
【问题描述】:

我有 XML 格式。我想从 xml 节点中删除特定的标签。怎么做。

XML 格式:

<?xml version="1.0"?>
<EmployeeResults>
  <MainArea>
    <CreationDateTime>2016-06-28T06:10:51.5215523Z</CreationDateTime>
  </MainArea>
  <SubArea>
    <Show>
      <ID>TEST1</ID>
    </Show>
    <ProductionPerformance>
      <ID>Fabrication_ERP_MES_DEM_1-A</ID>
      <ProductionResponse>
        <ID>123</ID>        
        <StartTime>0001-01-01T00:00:00Z</StartTime>
        <EndTime>0001-01-01T00:00:00Z</EndTime>
        <EmployeeResponse>
          <ID>LotEmployeeResponse</ID>          
          <ActualStartTime>2016-06-28T05:58:41.673Z</ActualStartTime>
          <ActualEndTime>0001-01-01T00:00:00Z</ActualEndTime>            
            <Quantity>
              <QuantityString>1</QuantityString>
            </Quantity>
          </MaterialActual>
          <TagName1>
            <ID>Test1</ID>
          </TagName1>
          <TagName2>
            <ID>Test2</ID>
          </TagName2>
        </EmployeeResponse>
      </ProductionResponse>
    </ProductionPerformance>
  </SubArea>
</EmployeeResults>

我想删除 TagName1 节点并为 TagName3 添加新的标签名称。如何删除和添加新节点。

请帮我解决这个问题。

【问题讨论】:

标签: c# xml


【解决方案1】:

应该这样做。 xmlInput 是您的 xml 作为字符串,使用 xpath 选择特定元素。 https://msdn.microsoft.com/en-us/library/d271ytdx(v=vs.110).aspx

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlInput);

XmlNode node = doc.SelectSingleNode("XPATh");


if (node != null)
{
   node.Remove();
}

【讨论】:

    【解决方案2】:

    我建议使用LinqXml

    XDocument doc= XDocument.Load(filepath);
    
    // Remove the element
    doc.Descendants("TagName1")
       .Remove();
    
    // Add new Element - Test3
    doc.Descendants("EmployeeResponse")
       .ElementAtOrDefault(0)
       .Add(new XElement("TagName3", new XElement("ID", "Test3")));
    

    查看Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-28
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多