如何将新节点添加到xml文件

时间:2013-10-09 21:32:15

标签: c# xml

我在向现有xml添加节点时遇到问题。我不确定节点是否是正确的名称。如果不是,有人可以纠正我。它要大得多,但这个例子可以解决问题。

这是xml文件的样子。

<?xml version="1.0" encoding="utf-8"?>
<MovieData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Movie>
        <Name>Death Race</Name>
        <Type>Action</Type>
        <Type>Adventure</Type>
        <Rating>R</Rating>
        <Disk>Blu-Ray</Disk>
    </Movie>
    <Movie>
        <Name>Death Race 2</Name>
        <Type>Action</Type>
        <Type>Adventure</Type>
        <Rating>R</Rating>
        <Disk>Blu-Ray</Disk>
    </Movie>
</MovieData>

现在我希望它最终会像这样。

<?xml version="1.0" encoding="utf-8"?>
<MovieData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Movie>
        <Name>Death Race</Name>
        <Type>Action</Type>
        <Type>Adventure</Type>
        <Rating>R</Rating>
        <Disk>Blu-Ray</Disk>
        <Time>time</Time>
    </Movie>
    <Movie>
        <Name>Death Race 2</Name>
        <Type>Action</Type>
        <Type>Adventure</Type>
        <Rating>R</Rating>
        <Disk>Blu-Ray</Disk>
        <Time>time</Time>
    </Movie>
</MovieData>

这是我到目前为止所拥有的。我希望能够在下面的代码中添加时间节点和值。

XmlDocument doc = new XmlDocument();
doc.Load(movieListXML);
XmlNode node = doc.SelectSingleNode("/MovieData");
foreach (XmlNode movie in node.SelectNodes("Movie"))
{
    if (movie != null)
    {
        // Do stuff here.
        // I'm not sure what to do here.
    }
}

这也不起作用。

XmlDocument doc = new XmlDocument();
doc.Load(movieListXML);
XmlNode node = doc.SelectSingleNode("/MovieData");
foreach (XmlNode movie in node.SelectNodes("Movie"))
{
    if (movie != null)
    {
        // Do stuff here.
        // I'm not sure what to do here.
        using(XmlWriter writer = node.CreateNavigator().AppendChild())
        {
            writer.WriteStartElement("SeriesType", movieListXML);
            writer.WriteElementString("Time", movieListXML, "time");
            writer.WriteEndElement();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

我通常使用Linq的XDocument来处理XML。您需要将System.Xml.Linq添加到using语句中。它会是这样的:

        string movieListXML = @"c:\test\movies.xml";
        XDocument doc = XDocument.Load(movieListXML);
        foreach (XElement movie in doc.Root.Descendants("Movie"))
        {
            movie.Add(new XElement("Time", "theTime"));
        }
        doc.Save(movieListXML);

答案 1 :(得分:0)

XmlDocument doc = new XmlDocument();
doc.Load(movieListXML);
XmlNode node = doc.SelectSingleNode("/MovieData");
foreach (XmlNode movie in node.SelectNodes("Movie"))
{
    if (movie != null)
    {
        XmlElement elem = doc.CreateElement("Time");
        elem.InnerText = "time";
        movie.AppendChild(elem);
    }
}
doc.Save(movieListXML);