FredyWenger
FredyWenger

Reputation: 2325

Problems to write xmlns entries with xmlwriter

I need exactly this header in my .xml-files:

<document xsi:schemaLocation="http://www.xxxxx.ch/schema/2.1 
http://www.xxxxx.ch/schema/xxxxx_2.1.01.xsd" 
xmlns="http://www.xxxxx.ch/schema/2.1" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

I’m not able to create the file as needed, as xmlwriter has thrown errors by all my tries (tried anything I found since a full day now).
What is missing here - how to generate the file as needed? Code snipped:

Dim settings As XmlWriterSettings = New XmlWriterSettings()
settings.Indent = True
settings.CloseOutput = True
Dim cFileExport As String = cTempAblagenPfad + cFilenameExport_XML
Using writer As XmlWriter = XmlWriter.Create(cFileExport, settings)
writer.WriteStartDocument()
'
writer.WriteStartElement("document")
writer.WriteAttributeString("xsi", "schemaLocation", vbNull, "http://www.xxxxx.ch/schema/2.1 http://www.xxxxx.ch/schema/xxxxx_2.1.01.xsd")
' Generates XML: <document xsi:schemaLocation="http://www.xxxxx.ch/schema/2.1 http://www.xxxxx.ch/schema/xxxxx_2.1.01.xsd" xmlns:xsi="1">
' I have no idea, why xmlns:xsi="1" is generated by the xml-writer - maybe that’s the problem?
writer.WriteAttributeString("xmlns", "http://www.xxxxx.ch/schema/2.1", XmlSchema.InstanceNamespace) 
' throws: "The prefix "xmlns" is reserved for XML
writer.WriteAttributeString("xmlns", "http://www.xxxxx.ch/schema/2.1") 
' throws: "the prefix '' cannot be changed from '' to 'http://www.xxxxx.ch/schema/2.1' in the same startelement tag"
 writer.WriteAttributeString("xmlns", "xsi", vbNull, "http://www.w3.org/2001/XMLSchema-instance")
‘throws: "The prefix "xmlns" is reserved for XML
....

Thanks for any hint..

Upvotes: 0

Views: 524

Answers (1)

FredyWenger
FredyWenger

Reputation: 2325

After a lot of try-and-error, I have found the solution myself:

The code:

Dim cNameSpace As String = "http://www.xxxxx.ch/schema/2.1"
Dim cSchemaInstance As String = "http://www.w3.org/2001/XMLSchema-instance"
'
Using writer As XmlWriter = XmlWriter.Create(cFileExport, settings)
  writer.WriteStartDocument()
  writer.WriteStartElement("document", cNameSpace) ------
  writer.WriteAttributeString("xmlns", "xsi", "http://www.w3.org/2000/xmlns/", cSchemaInstance)
  writer.WriteAttributeString("xsi", "schemaLocation", cSchemaInstance, "http://www.xxxxx.ch/schema/2.1 http://www.xxxxx.ch/schema/xxxxx_2.1.01.xsd")

Generates:

<document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
xsi:schemaLocation="http://www.xxxxx.ch/schema/2.1  
http://www.xxxxx.ch/schema/eSchKG_2.1.01.xsd"  
xmlns="http://www.xxxxx.ch/schema/2.1">

Not exactly the order as in the example, but this does not matter...
The file was now accepted as valid from the system, where I have to send the file to.

Upvotes: 1

Related Questions