我有以下格式的 XML 格式
<Tag>
Value
</Tag>
这来 self 无法更改的外部数据源。
使用 XmlReader
时,内容有 Linebreaks
和 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;
}
}
}
我怎样才能避免这种情况?
最佳答案
无效答案
这个答案似乎不起作用,但我暂时保留它以避免其他人提出建议。如果有人发布更好的答案,我会删除它。
您是否尝试设置 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
属性。
简单的回答
你可以直接调用 Trim
:
string value = reader.ReadElementContentAsString().Trim();
这不会删除 内容行之间的换行符,当然...如果您需要这样做,您始终可以使用 string.Replace
。
(正如我在评论中提到的,与 XmlReader
相比,我个人更喜欢使用 LINQ to XML,除非您真正阅读的内容太大而无法放入内存,但这是另一回事。)
关于c# - 读取 XML 时忽略空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16376414/