在xml文件c#的特定位置添加元素

本文关键字:定位 位置 添加 元素 xml 文件 | 更新日期: 2023-09-27 18:12:47

我有以下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> -元素中。

我如何指定在哪里添加新的元素,开始和结束标签,到一个xml文件在c#中?

我用XDocument

在xml文件c#的特定位置添加元素

尝试这样做,每个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

示例如下:link

下面是代码片段:
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);