我在将节点添加到现有 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();
}
}
}