我有一个XML文件,如下所示:
<catalog>
<cd Id="2">
<title>Title2</title>
<artist>artist2</artist>
<company>
<companyName>Company2</companyName>
<companyAddress1>street1</companyAddress1>
<companyAddress2>street2</companyAddress2>
<companyCity>City2</companyCity>
</company>
<price>12.90</price>
<year>1987</year>
</cd>
<cd Id="3">
<title>Title3</title>
<artist>artist3</artist>
<company>
<companyName>Company3</companyName>
<companyAddress1>street1</companyAddress1>
<companyAddress2>street2</companyAddress2>
<companyCity>City3</companyCity>
</company>
<price>9.90</price>
<year>1984</year>
</cd>
</catalog>
我想根据节点中的Id属性过滤此源XML,并创建一个新的XML文件,如:
<catalog>
<cd Id="2">
<title>Title2</title>
<artist>artist2</artist>
<company>
<companyName>Company2</companyName>
</company>
<price>12.90</price>
</cd>
<cd Id="3">
<title>Title3</title>
<artist>artist3</artist>
<company>
<companyName>Company3</companyName>
</company>
<price>9.90</price>
</cd>
</catalog>
源文件太大了,所以我想我需要使用XmlReader。但我无法找到一种基于Id过滤的简单方法并提取所需的节点。任何帮助表示赞赏。
由于
答案 0 :(得分:2)
我认为这正是你想要的:
XDocument xdoc = XDocument.Load("File path");//Load XML file
//Delete all elements in company except companyName
xdoc.Descendants("company").Elements().Where(x => x.Name != "companyName").Remove();
//Delete year
xdoc.Descendants("year").Remove();
xdoc.Save("File path");//Overwrite the XML file with the new result