2015-02-05 70 views
0

我在XML文件中的以下節點:無法刪除空的XML節點@「// * [不是(節點())]」

<PERSON> 
    <LEOKA_DATA> </LEOKA_DATA> 
</PERSON> 

我不能刪除LEOKA標籤使用以下代碼(片斷):

 string file = CommonVariables.MainDir + @"\Schemas\RemoveEmptyTags.xsl"; 
     try 
     { 
      XmlDocument xmlDocument = new XmlDocument(); 

      xmlDocument.Load(tempFile); //tempfile is the xml file 

      XmlNodeList emptyElements = xmlDocument.SelectNodes(@"//*[not(node())]"); 

      if (emptyElements != null) 

       for (int i = emptyElements.Count - 1; i >= 0; i--) 
       { 
        var parentNode = emptyElements[i].ParentNode; 

        if (parentNode != null) 
        { 
         if (emptyElements[i].Name != "LINE") 
          parentNode.RemoveChild(emptyElements[i]); 
        } 
       } 
     } 
     catch (FileNotFoundException ex) 
     { **something here** } 

然而,上面的代碼工作,如果該節點是象下面這樣(注意開始標記和結束標記之間沒有空格):

<LEOKA></LEOKA> 

我也嘗試使用下面的代碼,但沒有工作:

var doc = XDocument.Parse(tempfile); 

var emptyElements = from descendant in doc.Descendants() 
       where string.IsNullOrWhiteSpace(descendant.Value) 
       select descendant; 

emptyElements.Remove(); 

任何幫助將非常感激。如果您需要更多詳細信息,請告訴我。謝謝。

+0

可能的重複[按照包含使用XPath的空白值查找節點](http://stackoverflow.com/questions/393840/locating-the-node-by-value-containing-whitespaces-using-xpath) – 2015-02-05 14:56:24

+0

正在尋找一個包含空格的標籤,並且空白可以由多個字符組成,如' '用於製表符,或' '用於換行符等等。因此,即使是一個簡單的空格字符,也等於一個值。因此,它不會使用not(node())查找具有空格字符的節點。 – 2015-02-05 14:59:53

+0

即使使用字符串長度(text()),它也不起作用,因爲字符串的長度爲1,並帶有空格char。 – 2015-02-05 15:01:18

回答

0

如下我會修改你的XPath表達式:

XmlNodeList emptyElements = xmlDocument.SelectNodes(@"//*[not(node()[ 
    not(self::text()[normalize-space() = '']) 
    ])]"); 

換句話說,排除具有比一個空的文本節點,其中「空」指除空白,沒有任何文本值以外的子元素。