I’m using Linq to XML to format a very complex xml tree and am trying to format these lines below:
<?xml version="1.0" encoding="UTF-8" ?>
<MIF xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="mifv1.xsd" ISO-CODE="100028">
Below is my code:
Dim xmlTree As New XDocument(New XDeclaration("1.0", "UTF-8", "X"), _
New XElement("MIF", _
New XAttribute("xmlnsxsi", "http://www.w3.org/2001/XMLSchema-instance"), _
New XAttribute("xsinoNamespaceSchemaLocation", "mifv1.xsd"), _
New XAttribute("ISO-CODE", "100028"), _
New XElement(Me.NewContractNode())))
The XDocument / XDeclaration is working on formatting the 1st line. The 2nd line is more problematic, as the XAttribute name argument (xmlns:xsi) won’t accept a colon (:) character; as with the xsi:noNamespaceSchemaLocation.
I have a work around, where I convert xmlTree to a string and replace values with ones containing colons, but there are 2 problems with this:
1) it looses all the information from the XDeclaration, so I’m manually prepending it to my string
2) I now have to use StreamWriter instead of xmlTree.save() to write the result:
Dim sb As New StringBuilder
sb.Append("<?xml version=")
sb.Append(Chr(34))
sb.Append("1.0")
sb.Append(Chr(34))
sb.Append(" encoding=")
sb.Append(Chr(34))
sb.Append("UTF-8")
sb.Append(Chr(34))
sb.Append(" ?>")
sb.Append(xmlTree.ToString())
workXML = sb.ToString()
workXML = Replace(workXML, "xmlnsxsi", "xmlns:xsi")
workXML = Replace(workXML, "xsinoNamespaceSchemaLocation", "xsi:noNamespaceSchemaLocation")
outFile.WriteLine(workXML)
outFile.Close()
My workaround is working, but it seems to me that there must be a better way of doing this. I’d appreciate any suggestions.