我有這樣的XML文件中:做這個添加重複元素的XML文件
<root>
<Friend_2>
<MESSAGE_BODY>hi</MESSAGE_BODY>
<MESSAGE_SENDER_ID>1</MESSAGE_SENDER_ID>
<MESSAGE_RECEIVER_ID>2</MESSAGE_RECEIVER_ID>
<MESSAGE_CREATION_DATE>2014-08-29T15:33:18.1191004+03:00</MESSAGE_CREATION_DATE>
</Friend_2>
</root>
我使用這個功能,將元素添加到該文件:
private void createNode(string body, string senderid, string receiverid,DateTime creationDate,string path1,string path2)
{
XDocument doc1 = XDocument.Load(path1);
XDocument doc2 = XDocument.Load(path2);
XElement root1 = new XElement("Friend_"+receiverid);
XElement root2 = new XElement("Friend_"+senderid);
root1.Add(new XElement("MESSAGE_BODY", body));
root1.Add(new XElement("MESSAGE_SENDER_ID", senderid));
root1.Add(new XElement("MESSAGE_RECEIVER_ID", receiverid));
root1.Add(new XElement("MESSAGE_CREATION_DATE", creationDate));
root2.Add(new XElement("MESSAGE_BODY", body));
root2.Add(new XElement("MESSAGE_SENDER_ID", senderid));
root2.Add(new XElement("MESSAGE_RECEIVER_ID", receiverid));
root2.Add(new XElement("MESSAGE_CREATION_DATE", creationDate));
if (doc1.Root.Element(root1.Name.LocalName) == null)
{
doc1.Element("root").Add(root1);
}
if (doc2.Root.Element(root2.Name.LocalName) == null)
{
doc2.Element("root").Add(root2);
}
doc1.Save(path1);
doc2.Save(path2);
}
但原來的元素被替換。我希望我的XML文件是這樣的:
<root>
<Friend_2>
<MESSAGE_BODY>hi</MESSAGE_BODY>
<MESSAGE_SENDER_ID>1</MESSAGE_SENDER_ID>
<MESSAGE_RECEIVER_ID>2</MESSAGE_RECEIVER_ID>
<MESSAGE_CREATION_DATE>2014-08-29T15:33:18.1191004+03:00</MESSAGE_CREATION_DATE>
<MESSAGE_BODY>how r you ?</MESSAGE_BODY>
<MESSAGE_SENDER_ID>1</MESSAGE_SENDER_ID>
<MESSAGE_RECEIVER_ID>2</MESSAGE_RECEIVER_ID>
<MESSAGE_CREATION_DATE>2014-10-29T15:33:18.1191004+03:00</MESSAGE_CREATION_DATE>
</Friend_2>
</root>
我的主要理由,這個模式是因爲我使用的解析文檔,並返回一個包含4列和2行
public static DataSet ConvertXMLToDataTable(string xmlString)
{
DataSet dataset = new DataSet();
dataset.ReadXml(xmlString);
return dataset.Tables.Count > 0 ? dataset : null;
}
DataSet Chat_ds=Convertor.ConvertXMLToDataTable(path);
if (Chat_ds.Tables.Count > 0)
{
DataTable Chat_dt = Chat_ds.Tables["Friend_" + FriendID];
...................
一個DataTable的功能
我不能讓我的XML看起來像這樣:
<root>
<Friend_2>
<message>
<MESSAGE_BODY>hi</MESSAGE_BODY>
<MESSAGE_SENDER_ID>1</MESSAGE_SENDER_ID>
<MESSAGE_RECEIVER_ID>2</MESSAGE_RECEIVER_ID>
<MESSAGE_CREATION_DATE>2014-08-29T15:33:18.1191004+03:00</MESSAGE_CREATION_DATE>
</message>
<message>
<MESSAGE_BODY>how r you ?</MESSAGE_BODY>
<MESSAGE_SENDER_ID>1</MESSAGE_SENDER_ID>
<MESSAGE_RECEIVER_ID>2</MESSAGE_RECEIVER_ID>
<MESSAGE_CREATION_DATE>2014-10-29T15:33:18.1191004+03:00</MESSAGE_CREATION_DATE>
</message>
</Friend_2>
</root>
如果我明白,你實際上是重新創建Friend_2節點,所以是的,我希望它的內容被「替換」。 – Kilazur 2014-08-29 13:15:09
我該如何解決這個問題? – Sora 2014-08-29 13:20:31