2013-01-15 65 views
-1

我有一個XML文件,如下所示。我想用這個XML文件創建另一個XML文件,但是新的XML文件只能包含那些有值的標籤。例如 - 在下面的XML文件中,我有一個沒有城市和州的員工Sam,所以我的新XML文件不能包含這些空標籤。我是LINQ to XML的新手,但我的朋友說我可以使用LINQ to XML來實現它。任何幫助將不勝感激。使用非空標籤從另一個XML文件創建XML文件

謝謝。

<?xml version="1.0" encoding="utf-8" ?> 
     <Employees> 
     <Employee> 
<EmpId>1</EmpId> 
<Name>Sam</Name> 
<Sex>Male</Sex> 
<Phone Type="Home">423-555-0124</Phone> 
<Phone Type="Work">424-555-0545</Phone> 
      <Address> 
    <Street>7A Cox Street</Street> 
    <City></City> 
    <State></State> 
    <Zip>95220</Zip> 
    <Country>USA</Country> 
</Address> 
     </Employee> 
      <Employee> 
<EmpId>2</EmpId> 
<Name>Lucy</Name> 
<Sex>Female</Sex> 
<Phone Type="Home">143-555-0763</Phone> 
<Phone Type="Work">434-555-0567</Phone> 
<Address> 
    <Street>Jess Bay</Street> 
    <City>Alta</City> 
    <State>CA</State> 
    <Zip>95701</Zip> 
    <Country>USA</Country> 
</Address> 
    </Employee> 
     <Employee> 
<EmpId>3</EmpId> 
<Name>Kate</Name> 
<Sex>Female</Sex> 
<Phone Type="Home">166-555-0231</Phone> 
<Phone Type="Work">233-555-0442</Phone> 
<Address> 
    <Street>23 Boxen Street</Street> 
    <City>Milford</City> 
    <State>CA</State> 
    <Zip>96121</Zip> 
    <Country>USA</Country> 
</Address> 
    </Employee> 
      <Employee> 
<EmpId>4</EmpId> 
<Name>Chris</Name> 
<Sex>Male</Sex> 
<Phone Type="Home">564-555-0122</Phone> 
<Phone Type="Work">442-555-0154</Phone> 
<Address> 
    <Street>124 Kutbay</Street> 
    <City>Montara</City> 
    <State>CA</State> 
    <Zip>94037</Zip> 
    <Country>USA</Country> 
</Address> 

+0

http://stackoverflow.com/questions/7318408/remove-empty-xml-tags –

+0

您可能會發現[此鏈接](http://mattgemmell.com/ 2008/12/08/what-you-you-tried /)有用 –

+0

感謝Sam Leach。 – user1301587

回答

1
XDocument xdoc = XDocument.Load(path_to_xml); 
xdoc.Descendants("Employee") 
    .Where(e => e.Descendants().Any(d => String.IsNullOrEmpty(d.Value))) 
    .Remove(); 
xdoc.Save(path_to_xml); 
+0

順便說一句'd.IsEmpty'將返回'content == null'。在這種情況下'd.Value'只需返回'String.Empty',它也會匹配條件'String.IsNullOrEmpty(d.Value)'。所以,你不需要同時使用'd.IsEmpty'和'String.IsNullOrEmpty(d.Value)'。同樣,'d.IsEmpty'將爲您的空標籤返回'false',因爲它們有空格。 –