0

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

这是 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();
        }
    }
}
4

2 回答 2

2

我通常使用 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);
于 2013-10-09T22:04:36.730 回答
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);
于 2013-10-09T21:39:55.540 回答