簡體   English   中英

如何使用C#在Xml中刪除空值子節點

[英]How to remove null valued child nodes in Xml using c#

我有一個由父節點和子節點組成的XML Documnet,

<?xml version='1.0' encoding='UTF-8'?> 
<response>   
   <system_timestamp>2016-10-21 13:40:28</system_timestamp>
   <response_data>   
    <status>Active</status>   
    <profile>     
     <first_name>John</first_name>
     <last_name>Abraham</last_name>
     <ship_to_address>        
      <address_1>null</address_1>      
      <address_2>null</address_2>  
      <city>null</city>      
      <state>null</state>   
      <postal_code>null</postal_code> 
     </ship_to_address>  
    </profile>
  </response_data>  
</response>

我有一些空值子節點,例如<address_1><address_2> 因此,現在我將如何刪除子節點的那些空值。 我試過了

doc.Descendants().Where(e => string.IsNullOrEmpty(e.Value)).Remove();

但這是行不通的。 我正在使用這個XmlDocument doc = new XmlDocument(); doc.LoadXml(_value); XmlDocument doc = new XmlDocument(); doc.LoadXml(_value);

代碼來解析xml文檔。 我們還有其他使用XMLDocument代替XElement刪除的方法嗎?

e.Value不是空引用或空字符串-它是字符串"null"因為這是元素中的值。

你要:

doc.Descendants().Where(e => (string) e == "null").Remove();

從列表中刪除一個項目時,您必須從最后一個項目刪除到第一個項目,否則索引將被搞砸,並且並非所有項目都被刪除。 嘗試這個

sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            List<XElement> nulls = doc.Descendants().Where(x => (string)x == "null").ToList();
            for (int i = nulls.Count - 1; i >= 0; i--)
            {
                nulls[i].Remove();
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM