0

I basically have this Code in VB.NET

xmlline = "<elements>etc..</elements> <!-- Some random Comment -->"
Dim XMLInput As XElement
XMLInput = XElement.Parse(xmlline)

and the comment is throwing and exception however i place it. As both "double root element" and "unexpected end of comment"

and have seen some suggesting to be using this reader instead with the optional parameter

Dim xmlsettings As New XmlReaderSettings With {
    .IgnoreComments = True
}
XmlReader.Create(XMLtextfile, xmlsettings)

but cant get it to work, and furthermore, the Xelement way of accessing the different parts of the tree is working so good for me.

like doing this: Dim XMLROOT As XElement = XMLInput.Element("ImportData").Element("UsagePoints").Element("UsagePoint") XMLROOT.Element("Address").Element("Street").Value

So how can i read XML textfiles containing XML structure with comments without getting an error ?

  • [Remove all comments from XDocument](https://stackoverflow.com/a/21955299/7444103) -- [XComment](https://learn.microsoft.com/en-us/dotnet/api/system.xml.linq.xcomment) class. – Jimi Oct 21 '20 at 12:34
  • The sample line is incorrect and shouldn't parse. See answer below. – dbasnett Oct 21 '20 at 13:02

2 Answers2

0

The string MUST be proper XML to work.

    Dim xmlline As String = "<elements><t>foo</t><t>bar</t><!-- Some random Comment --></elements>"
    Dim XMLInput As XElement
    XMLInput = XElement.Parse(xmlline)

edit:

    Dim comment As String = "Some random Comment"
    Dim xmlline As String = "<elements><t>foo</t><t>bar</t></elements>"
    Dim XMLInput As XElement
    XMLInput = XElement.Parse(xmlline)

    Dim xdoc As New XDocument(XMLInput)
    xdoc.Add(New XComment(comment))
dbasnett
  • 11,334
  • 2
  • 25
  • 33
  • 1
    nope, comments outside the elements is allowed in the XML standard https://www.w3.org/TR/xml/ i just need to sanitize it cuz te XElement.parse function cant handle it, so how to. – deployHuman Oct 21 '20 at 14:24
  • @Gabriel - the standard says, "...in a document outside other markup;" XElement is NOT a document. See edit for possible work around. – dbasnett Oct 21 '20 at 17:33
  • Thats adding a comment ? but now i understand that Xdocument can remove all comments as per @jimi ´s link, and it worked like a charm. And in the XML, the – deployHuman Oct 22 '20 at 07:10
0

Thanks to @jimi in the comments to pointing me to the answer in this link Remove all comments from XDocument

This is how i solved it:

Dim fs As New FileStream(myfiles(y).FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim sr As New StreamReader(fs)
line = sr.ReadToEnd
Dim doc As XDocument = XDocument.Parse(line)
doc.DescendantNodes.OfType(Of XComment).Remove
line = doc.ToString

and yes, i cant use the LOAD function in xdocument or any other cuz the file i´m trying to read is in use by another process, but this works like a charm!