如何将XML子节点添加到父节点C#
我当前的xml文件如下:
<?xml version="1.0" encoding=""?>
<sheet1>
<rd>
<id>45</id>
<name>alex</name>
<last>chali</last>
<phone>33666998565</phone>
<refF>
<adresse>41301 US Hwy 280, Sylacauga AL 35150</adresse>
<citie>NY</citie>
</refF>
<age>30</age>
<mp>
<degree>2</degree>
</mp>
<dpa>1</dpa>
</rd>
<rd>
<id>89</id>
<name>anna</name>
<last>marie</last>
<phone>336465798465</phone>
<refF>
<adresse>30 Memorial Drive, Avon MA 2322</adresse>
<citie>LA</citie>
</refF>
<age>28</age>
<mp>
<degree>2</degree>
</mp>
<dpa>1</dpa>
</rd>
</sheet1>
正在寻找:
<?xml version="1.0" encoding=""?>
<sheet1>
**<table> // i want that contain all table rows**
<rd>
<id>45</id>
<name>alex</name>
<last>chali</last>
<phone>33666998565</phone>
<refF>
<adresse>41301 US Hwy 280, Sylacauga AL 35150</adresse>
<citie>NY</citie>
</refF>
<age>30</age>
<mp>
<degree>2</degree>
</mp>
<dpa>1</dpa>
</rd>
**</table>**
</sheet1>
这是我的代码:
string header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Sheet1></Sheet1>";
XDocument doc = XDocument.Parse(header);
XElement sheet1 = doc.Root;
foreach (DataRow row in dt.AsEnumerable())
{
XElement rd = new XElement("rd", new object[] {
new XElement("id", row["id"]),
new XElement("name", row["name"]),
new XElement("last", row["last"]),
new XElement("phone", row["phone"]),
new XElement("refF", new object[] {
new XElement("adresse", row["adresse"]),
new XElement("citie", row["citie"]),
}),
new XElement("age", row["age"]),
new XElement("mp", new XElement("degree", row["mp"])),
new XElement("dpa", row["dpa"])
});
sheet1.Add(rd);
}
doc.Save(FILENAME);
}
代码显示'sheet1'作为包含'rd'的根元素,但实际上我希望它作为'table中的子元素。我应该如何重组?注意,我只能使用xDocument,不能使用xmlDocument
1-您可以将table
标签添加到header
,例如: