![](/img/trans.png)
[英]C#: How to add xml element at specific position in multiple records of xml file
[英]Add element at specific position in XML-file C#
我有以下XML文件:
<?xml-stylesheet type="text/xsl" href="transform.xslt"?>
<Root>
<Notes>
<Note>
<date>1997-07-04T00:00:00</date>
</Note>
<Note>
<date>1997-07-04T00:00:00</date>
</Note>
</Notes>
</Root>
不,我想像下面的代碼一樣向此XML添加元素:
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="transform.xslt"?>
<Root>
<Notes>
<notedate date="date here"><Note>
<date>1997-07-04T00:00:00</date>
</Note></notedate>
<notedate date="date here"><Note>
<date>1997-07-04T00:00:00</date>
</Note></notedate>
</Notes>
</Root>
如您所見,我想將<Note>
封裝在<notedate>
內。
如何在C#中指定在何處將新元素(開始和結束標簽)添加到XML文件?
我正在使用XDocument。
這里展示了一個簡單的案例: 鏈接
這是代碼片段:
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book genre='novel' ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"</book>");
XmlNode root = doc.DocumentElement;
//Create a new node.
XmlElement elem = doc.CreateElement("price");
elem.InnerText="19.95";
//Add the node to the document.
root.AppendChild(elem);
Console.WriteLine("Display the modified XML...");
doc.Save(Console.Out);
嘗試如下操作,替換每個Note元素:
var query=from n in xml.Root.Descendants("Note")
select n;
foreach(var elem in query.ToList())
elem.ReplaceWith(new XElement("notedate", new XAttribute("date", "date here"), elem));
您實際上想用另一個元素包裝每個Note
元素,一種選擇是使用ReplaceWith
:
var noteElements = doc.Root.Descendants("Note").ToList();
foreach(XElement noteEl in noteElements)
{
string noteDateValue = noteEl.Element("date").Value;
noteEl.ReplaceWith(new XElement("notedate", noteEl, new XAttribute("date", noteDateValue)));
}
// your doc is now updated
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.