问题描述
我基本上在VB.NET中有此代码
xmlline = "<elements>etc..</elements> <!-- Some random Comment -->"
Dim XMLInput As XElement
XMLInput = XElement.Parse(xmlline)
,并且引发评论和异常,但是我将其放置。 作为“双根元素”和“注释的意外结尾”
,并且看到一些建议使用此阅读器,而不是使用可选参数
Dim xmlsettings As New XmlReaderSettings With {
.IgnoreComments = True
}
XmlReader.Create(XMLtextfile,xmlsettings)
但是无法使它正常工作,而且,Xelement访问树的不同部分的方式对我来说是如此有效。
喜欢这样做:Dim XMLROOT As XElement = XMLInput.Element("ImportData").Element("UsagePoints").Element("UsagePoint")
XMLROOT.Element("Address").Element("Street").Value
那么我如何在不出错的情况下读取包含带有注释的XML结构的XML文本文件?
解决方法
字符串必须是正确的XML才能使用。
Dim xmlline As String = "<elements><t>foo</t><t>bar</t><!-- Some random Comment --></elements>"
Dim XMLInput As XElement
XMLInput = XElement.Parse(xmlline)
编辑:
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))
,
感谢@jimi在评论中为我指出此链接中的答案 Remove all comments from XDocument
这是我解决的方法:
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
是的,我不能在xdocument或任何其他cuz中使用LOAD函数,因为我试图读取的文件正被另一个进程使用,但这就像一个魅力!