我在將節點添加到現有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();
}
}
}
我覺得這個問題只是回答[這裏](http://stackoverflow.com/questions/14798854/c-xml-adding-new-nodes) – Tinwor
看上面看看我試過它仍然不起作用。 – deathismyfriend