C# 如何向xml文件添加新节点
我在向现有xml添加节点时遇到问题。我不确定node是否是正确的名称。如果不是,请有人纠正我。它要大得多,但这个例子应该可以做到这一点 下面是xml文件的外观C# 如何向xml文件添加新节点,c#,xml,C#,Xml,我在向现有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"> <
<?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>
这也不行
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();
}
}
}
我通常使用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);
我想这个问题刚刚得到了回答,看看上面我试了什么,它仍然不起作用。什么都没发生。我没有收到错误,文件中没有添加任何内容。可能您忘记添加字符串movieListXML=@“c:\test\movies.xml”;不,我不确定发生了什么,但我得到了上面的答案。谢谢你的帮助。
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();
}
}
}
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);
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);