2015-05-15 17 views
0

試圖找出如何添加屬性名稱和更多節點。到目前爲止的代碼:指定屬性名稱並添加子文件

'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> 
+0

我編輯了您的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –

+0

@約翰桑德斯,對不起。我會確保今後不要這樣做。 – Gmac

回答

1

<Views>元素添加屬性,您需要作爲一個元素來處理它。一旦你有一個元素,你只需使用​​。

'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) 
+0

謝謝!很好去! – Gmac

相關問題