摆脱XML中的无效字符。 [英] Getting rid of invalid character in XML.

查看:62
本文介绍了摆脱XML中的无效字符。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我试图解析XML文档时,它会有一个无效的字符,我希望能够删除它而不必自己进入文档。这是我得到的错误" System.Xml.XmlException:
'_',十六进制值0x02 ,是一个无效的字符。"对于以下XML行 -  
< command user =""名称= QUOT;"命令= QUOT; " />

When i am trying to parse a XML document from time to time it will have an invalid character i would like to be able to remove this without having to go into the document myself. This is the error i get "System.Xml.XmlException: '_', hexadecimal value 0x02, is an invalid character." for the following line of XML - <command user="" name="" command="" />

提前感谢您的帮助。

推荐答案

 那么做什么你手动修复它吗?

 So what do you do to fix it when you do it manually?

 显然某个地方有一个无效字符被添加到文件中,或者你正在创建文件和插入不知怎的,这个角色不知何故。 这将是解决问题的最佳位置,因此
永远不会被放入xml文件中。

 Apparently somehow there is an invalid character being added to the document along its way to you or maybe you are creating the file and inserting this character somehow without knowing it.  That would be the best place to fix the problem so it never gets put in the xml file to begin with.

 然而, 也许你无法控制文件的创建。 在那种情况下, 一个Xml文件基本上只是一个美化的文本文件,您可以使用标准文本文件
方法打开并替换所有(Chr(2)或Chr(& H02))字符, 然后将其保存回硬盘。 您可以设置这样的内容来查找字符,并在打开并使用xml方法读取之前根据需要替换它。

 However,  maybe you have no control over the creation of the file.  In that case,  an Xml file is basically just a glorified text file which you can open and replace all the (Chr(2) or Chr(&H02)) characters using standard text file methods,  then save it back to the hard drive.  You could set something like this up to look for the character and replace it if needed before opening and reading it with the xml methods....

Imports System.Xml

Public Class Form1
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim fileChars() As Char = IO.File.ReadAllText("C:\TestFolder\MyFile.xml", System.Text.Encoding.UTF8).ToCharArray
        If fileChars.Where(Function(x) Not XmlConvert.IsXmlChar(x)).Count > 0 Then
            fileChars = fileChars.Where(Function(x) XmlConvert.IsXmlChar(x)).ToArray
            IO.File.WriteAllText("C:\TestFolder\MyFile.xml", fileChars, System.Text.Encoding.UTF8)
        End If
        fileChars = Nothing

        'now open and read the xml file...
    End Sub
End Class


这篇关于摆脱XML中的无效字符。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆