合并文档中的XML节点

我有一个由MS Excel创build的XML文档。 我想要的是组合节点相同的ID。 我目前的XML是这样的:

<ns1:publications> <ns1:book id="3" subType="book"> <ns1:peerReviewed>false</ns1:peerReviewed> <ns1:publicationCategory>scientific</ns1:publicationCategory> <ns1:publicationStatus>published</ns1:publicationStatus> <ns1:language>en_GB</ns1:language> <ns1:title> <ns2:text lang="en" country="EN">Kirja3</ns2:text> </ns1:title> <ns1:abstract> <ns2:text lang="en" country="EN"> </ns1:abstract> <ns1:persons> <ns1:author> <ns1:role>author</ns1:role> <ns1:person external="false" id="3"> <ns1:firstName>Rob</ns1:firstName> <ns1:lastName>Hubbard</ns1:lastName> </ns1:person> </ns1:author> </ns1:persons> <ns1:organisations> <ns1:organisation id="220400"/> </ns1:organisations> <ns1:owner id="220400"/> <ns1:publicationDate> <ns2:year>2014</ns2:year> </ns1:publicationDate> <ns1:visibility>Public</ns1:visibility> <ns1:numberOfPages>655</ns1:numberOfPages> <ns1:placeOfPublication>Newcastle</ns1:placeOfPublication> </ns1:book> <ns1:book id="3"> <ns1:title/> <ns1:abstract/> <ns1:persons> <ns1:author> <ns1:person id="4"> <ns1:firstName>Chris</ns1:firstName> <ns1:lastName>Steward</ns1:lastName> </ns1:person> </ns1:author> </ns1:persons> <ns1:organisations> <ns1:organisation id="220400"/> </ns1:organisations> <ns1:owner id="220400"/> <ns1:publicationDate/> </ns1:book> 

它应该是这样的:

 <ns1:publications> <ns1:book id="3" subType="book"> <ns1:peerReviewed>false</ns1:peerReviewed> <ns1:publicationCategory>scientific</ns1:publicationCategory> <ns1:publicationStatus>published</ns1:publicationStatus> <ns1:language>en_GB</ns1:language> <ns1:title> <ns2:text lang="en" country="EN">Kirja3</ns2:text> </ns1:title> <ns1:abstract> <ns2:text lang="en" country="EN"> </ns1:abstract> <ns1:persons> <ns1:author> <ns1:role>author</ns1:role> <ns1:person external="false" id="3"> <ns1:firstName>Rob</ns1:firstName> <ns1:lastName>Hubbard</ns1:lastName> </ns1:person> </ns1:author> <ns1:author> <ns1:person external="false" id="4"> <ns1:firstName>Chris</ns1:firstName> <ns1:lastName>Steward</ns1:lastName> </ns1:person> </ns1:author> </ns1:persons> <ns1:organisations> <ns1:organisation id="220400"/> <ns1:organisation id="220300"/> </ns1:organisations> <ns1:owner id="220400"/> <ns1:publicationDate> <ns2:year>2014</ns2:year> </ns1:publicationDate> <ns1:visibility>Public</ns1:visibility> <ns1:numberOfPages>655</ns1:numberOfPages> <ns1:placeOfPublication>Newcastle</ns1:placeOfPublication> </ns1:book> 

数据来自Excel电子表格,其中包含有关行的信息。 例如,book可以有多个作者,并且它们在第一列上具有相同id的不同行上。

我build议你使用XML序列化从XML导入你的数据,通过C#类操纵你的数据,并以XML格式输出。 看到这个职位了解更多信息。

这就是你如何阅读:

 MyClass myObject = new MyClass; XmlSerializer ser = new XmlSerializer(myObject.GetType()); using (FileStream fs = new FileStream(FilePath, FileMode.Open)) { XmlTextReader reader = new XmlTextReader(fs); myObject = (MyClass)ser.Deserialize(reader); } 

一旦获得了类,就可以很容易地通过linq或循环来合并/删除节点。