分配属性名称并添加子项

时间:2015-05-15 17:42:51

标签: xml vb.net

试图弄清楚如何添加属性名称和更多节点。代码到目前为止:

'Create the xmlDoc with Views root
Dim doc As New XmlDocument
doc.LoadXml("<Views></Views>")

'Add a View element
Dim vElem As XmlElement = doc.CreateElement("View")
vElem.InnerXml = "Name"
vElem.InnerText = "vACCESS"
doc.DocumentElement.AppendChild(vElem)

'Set writer settings
Dim sett As New XmlWriterSettings
sett.Indent = True

'Save file and indent
Dim sw As XmlWriter = XmlWriter.Create("d:\input\data.xml", sett)
doc.Save(sw)

我得到了这个:

<?xml version="1.0" encoding="utf-8"?>
<Views>
    <View>vACCESS</View>
</Views>

但我想要的是:

<?xml version="1.0" encoding="utf-8"?>
<Views Code="Sample1">
    <View Name="vACCESS">
        <Criteria>ACCESS</CRITERIA>
    </View>
</Views>

1 个答案:

答案 0 :(得分:1)

要在<Views>元素上添加属性,您需要获取它作为元素的句柄。拥有元素后,只需使用element.SetAttribute("Name", "Value")

'Create the xmlDoc with Views root
Dim doc As New XmlDocument
doc.LoadXml("<Views></Views>")

'Enumerate the root element and add the attribute
Dim rElem As XmlElement = doc.FirstChild
rElem.SetAttribute("Code", "Sample1")

'Add a View element and attribute
Dim vElem As XmlElement = doc.CreateElement("View")
vElem.SetAttribute("Name", "vACCESS")

Dim cElem As XmlElement = doc.CreateElement("Criteria")
cElem.InnerText = "ACCESS"

vElem.AppendChild(cElem)

doc.DocumentElement.AppendChild(vElem)

'Set writer settings
Dim sett As New XmlWriterSettings
sett.Indent = True

'Save file And indent
Dim sw As XmlWriter = XmlWriter.Create("c:\temp\data.xml", sett)
doc.Save(sw)