vb.net 向 XML 插入新元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14643888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert new element to XML
提问by JLRishe
I have a program that inserts a new lesson to a course XML. Here is the XML file:
我有一个程序可以将新课程插入课程 XML。这是 XML 文件:
Course.xml
<Courses>
<Course>
<Name>ABC course</Name>
<Lessons>
<Lesson>
<Lesson_name>Learn ABC!</Lesson_name>
<Lesson_date>XX/XX/XXXX</Lesson_date>
</Lesson>
'WANT TO ADD A LESSON HERE!!!
</Lessons>
</Course>
<Course>
<Name>DEF Course</Name>
<Lesson>
<Lesson_name>Learn DEF!</Lesson_name>
<Lesson_date>XX/XX/XXXX</Lesson_date>
</Lesson>
</Course>
</Courses>
I would want to insert a lesson with all those nodes such as Lesson, Lesson_date, Lesson_nameetc. without affecting the existing lessons and other elements. Is there any simple way?
我想插入一个教训与所有那些节点,如Lesson,Lesson_date,Lesson_name等不影响现有的经验教训和其他元素。有什么简单的方法吗?
回答by JLRishe
Something like this should work:
这样的事情应该工作:
Dim xmlDoc As XmlDocument = New XmlDocument()
xmlDoc.Load("Course.xml")
Dim courseName = "ABC course"
With xmlDoc.SelectSingleNode("/Courses/Course[Name = '" & courseName & "']/Lessons").CreateNavigator().AppendChild()
.WriteStartElement("Lesson")
.WriteElementString("Lesson_name", "Learn something else!")
.WriteElementString("Lesson_date", "YY/YY/YYYY")
.WriteEndElement()
.Close()
End With
If you want to modify the actual file, you could use xmlDoc.Save()after that.
如果要修改实际文件,可以xmlDoc.Save()在此之后使用。
回答by andy
By using the DataSet.ReadXml Methodyou can do this. Change the values in Dataset table and use DataSet.WriteXml Method.
通过使用DataSet.ReadXml 方法,您可以做到这一点。更改 Dataset 表中的值并使用DataSet.WriteXml Method。

