如何忽略 XML 文件中的前导空格?
我需要将 xml 从文件加载到 XmlDocument 中。问题是该文件包含一些前导空格。 (我无法控制生成该文件的系统。) 有没有任何干净/简单的方法来忽略或删除这些字符?
string SamplelRequestFile = @"C:\example.xml";
XmlDocument docXML = new XmlDocument();
XmlTextReader xReader = new XmlTextReader(SamplelRequestFile);
XmlReaderSettings ReaderSettings = new XmlReaderSettings();
ReaderSettings.XmlResolver = null;
ReaderSettings.ProhibitDtd = false;
docXML.Load(xReader);
example.xml(注意前导空格)
<?xml version="1.0" ?>
<myRoot>
<someElement />
</myRoot>
I need to load xml from a file into an XmlDocument. The problem is that the file contains some leading whitespace. (I have no control over the system that produces the file.)
Is there any clean/easy way to ignore or strip those characters?
string SamplelRequestFile = @"C:\example.xml";
XmlDocument docXML = new XmlDocument();
XmlTextReader xReader = new XmlTextReader(SamplelRequestFile);
XmlReaderSettings ReaderSettings = new XmlReaderSettings();
ReaderSettings.XmlResolver = null;
ReaderSettings.ProhibitDtd = false;
docXML.Load(xReader);
example.xml (note the leading spaces)
<?xml version="1.0" ?>
<myRoot>
<someElement />
</myRoot>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你只需要做类似的事情
You'll just have to do something like
这是一个有效的示例:
here is a sample that works:
这是无效的 XML。
根据 XML 规范,pi 或 处理指令 必须是第一个字符(如果存在)。
我建议您通过修剪 XML 来预处理 XML。
解决方法:
This is an invalid XML.
According to XML Specification, pi or processing-instructions must be the first characters if they are present.
I suggest you pre-process the XML by trimming the XML.
Workaround:
自己在文件上创建一个
Stream
和一个StreamReader
,然后使用Peek()
并在看到空格时使用流中的字符。确定下一个字符是<
后,将流传递给XmlTextReader
构造函数。Create a
Stream
and aStreamReader
on the file yourself, thenPeek()
and consume characters from the stream as long as you see whitespace. Once you're sure that the next character is<
, pass the stream to theXmlTextReader
constructor.您是否尝试过添加此标志?
Have you tried adding this flag ?