忽略的空白,同时读取XML [英] Ignore whitespace while reading XML
问题描述
我有一个XML格式的格式如下
I have an XML format with following format
<Tag>
Value
</Tag>
这来自外部数据源,我不能改变。
当使用的XmlReader
的内容具有换行符
和 Whitepace
。
This comes from an external datasource I cannot change.
When using XmlReader
the content has Linebreaks
and Whitepace
.
XmlReaderSettings xmlSettings = new XmlReaderSettings();
xmlSettings.Schemas = new System.Xml.Schema.XmlSchemaSet();
XmlReader schemaReader = XmlReader.Create(xsdStream);
xmlSettings.Schemas.Add("", schemaReader);
xmlSettings.ValidationType = ValidationType.Schema;
reader = XmlReader.Create(xmlFilename, xmlSettings);
// Parse the XML file.
while (reader.Read())
{
if (reader.IsStartElement())
{
switch (reader.Name)
{
case "Tag":
string value = reader.ReadElementContentAsString();
Console.WriteLine(value);
break;
}
}
}
我怎样才能避免这种情况?
How can I avoid this?
推荐答案
不工作答案
这答案似乎并不工作,但我要离开它的那一刻,以避免其他人提出的建议。我会删除,如果有人发布一个更好的答案。
This answer doesn't seem to work, but I'm leaving it for the moment to avoid anyone else suggesting it. I'll delete this if someone posts a better answer.
你有没有尝试设置 XmlReaderSettings.IgnoreWhitespace
?
Did you try setting XmlReaderSettings.IgnoreWhitespace
?
这是不被认为是显著白色空间包括空格,制表符,并用来分开标记以获得更好的可读性空行。这样的一个例子是在元素内容的空白。
White space that is not considered to be significant includes spaces, tabs, and blank lines used to set apart the markup for greater readability. An example of this is white space in element content.
由于某种原因,这种的不的影响 ReadElementContentAsString
甚至值
属性一个文本节点。
For some reason this doesn't affect ReadElementContentAsString
or even the Value
property of a text node.
简单的答案
您可以只调用修剪
:
string value = reader.ReadElementContentAsString().Trim();
这将不删除换行符的在的contentful线,当然...如果你需要做的是,你总是可以使用与string.replace
。
That won't remove line breaks between contentful lines, of course... if you need to do that, you could always use string.Replace
.
(正如我在注释中,我会亲自$使用LINQ to XML比的XmlReader
除非你真正阅读的东西太大,不适合P中$ PFER记忆,但那是另一回事。)
(As I mentioned in the comment, I'd personally prefer using LINQ to XML than XmlReader
unless you're genuinely reading something too large to fit in memory, but that's a separate matter.)
这篇关于忽略的空白,同时读取XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!