读取 XML 时忽略空格

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

上一篇:带有检查空元素的 XML 到 LINQ 下一篇:使用 System.IdentityModel.Tokens.Jwt 使用 RS512 验证 JWT 签名

相关文章