問題描述
我有以下格式的 XML 格式
I have an XML format with following format
<Tag>
Value
</Tag>
這來自我無法更改的外部數據源.使用 XmlReader
時,內容有 Linebreaks
和 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
甚至是文本節點的 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 時忽略空格的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!