japesu
japesu

Reputation: 134

Inserting both XmlDocumentType and XmlDeclaration to XmlDocument

I have some trouble creating my XmlDocument class. This is what I've tried to do:

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)

This will result in error: Cannot insert the node in the specified location. Line throwing this error is myDoc.InsertBefore(xmldecl, root)

Just cannot figure out this. Which order should I insert these elements? I've tried different orders but I think I'm just doing something totally wrong and this shouldn't even work in the first place :) But then how to do this?

Upvotes: 1

Views: 1789

Answers (1)

Steven Doggart
Steven Doggart

Reputation: 43743

This works for me:

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)

Note that the root element name must be the same as the name parameter given to XmlDocument.CreateDocumentType.

You may find, however, that for building an XML document from scratch like this, it's easier to just use the 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

Upvotes: 1

Related Questions