读取 XML 时忽略空格

Ignore whitespace while reading XML(读取 XML 时忽略空格)
本文介绍了读取 XML 时忽略空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有以下格式的 XML 格式

I have an XML format with following format

<Tag>
    Value
</Tag>

这来自我无法更改的外部数据源.使用 XmlReader 时,内容有 LinebreaksWhitepace.

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 甚至是文本节点的 Value 属性.

For some reason this doesn't affect ReadElementContentAsString or even the Value property of a text node.

简单回答

你可以调用 Trim:

string value = reader.ReadElementContentAsString().Trim();

这不会删除 内容行之间的换行符,当然...如果您需要这样做,您可以随时使用 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 除非你真的在阅读太大而无法放入内存的东西,但这是另一回事.)

(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 时忽略空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Custom Error Queue Name when using EasyNetQ for RabbitMQ?(使用 EasyNetQ for RabbitMQ 时自定义错误队列名称?)
How to generate password_hash for RabbitMQ Management HTTP API(如何为 RabbitMQ 管理 HTTP API 生成密码哈希)
Rabbitmq Ack or Nack, leaving messages on the queue(Rabbitmq Ack 或 Nack,将消息留在队列中)
Wait for a single RabbitMQ message with a timeout(等待一条带有超时的 RabbitMQ 消息)
Setup RabbitMQ consumer in ASP.NET Core application(在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者)
Specify Publish timeouts in mass transit(指定公共交通中的发布超时)