2012-12-18 15 views
1

我在創建我的XmlDocument類時遇到了一些麻煩。這是我試圖做的:將XmlDocumentType和XmlDeclaration插入到XmlDocument

Dim myDoc = New XmlDocument() 

Dim docType As XmlDocumentType = myDoc.CreateDocumentType("DtdAttribute", Nothing, "DtdFile.dtd", Nothing) 
myDoc.XmlResolver = Nothing 
myDoc.AppendChild(docType) 

Dim xmldecl As XmlDeclaration = myDoc.CreateXmlDeclaration("1.0", Encoding.GetEncoding("ISO-8859-15").BodyName, "yes") 

Dim root As XmlElement = myDoc.CreateElement("RootElement") 

myDoc.AppendChild(root) 
myDoc.InsertBefore(xmldecl, root) 

這將導致錯誤:無法在指定位置插入節點。投擲此錯誤的線是myDoc.InsertBefore(xmldecl, root)

只是無法弄清楚這一點。我應該插入這些元素的哪個順序?我嘗試過不同的命令,但我認爲我只是在做一些完全錯誤的事情,而這應該不會在第一時間起作用:)但是,如何做到這一點?

回答

1

這個工作對我來說:

Dim myDoc As New XmlDocument() 
Dim xmldecl As XmlDeclaration = myDoc.CreateXmlDeclaration("1.0", Encoding.GetEncoding("ISO-8859-15").BodyName, "yes") 
myDoc.AppendChild(xmldecl) 
Dim docType As XmlDocumentType = myDoc.CreateDocumentType("DtdAttribute", Nothing, "DtdFile.dtd", Nothing) 
myDoc.XmlResolver = Nothing 
myDoc.AppendChild(docType) 
Dim root As XmlElement = myDoc.CreateElement("DtdAttribute") 
myDoc.AppendChild(root) 

注意根元素名稱必須相同,若XmlDocument.CreateDocumentTypename參數。

你可能會發現,但是,從頭開始構建XML文檔這樣的,它更容易只需使用XmlTextWriter

Using writer As New XmlTextWriter("C:\Test.xml", Encoding.GetEncoding("ISO-8859-15")) 
    writer.WriteStartDocument() 
    writer.WriteDocType("DtdAttribute", Nothing, "DtdFile.dtd", Nothing) 
    writer.WriteStartElement("DtdAttribute") 
    writer.WriteEndElement() 
    writer.WriteEndDocument() 
End Using 
+0

嘿,它的工作:)非常感謝你。目前我有一個使用XmlDocument的大類,所以需要堅持下去;) – japesu