問(wèn)題描述
我有以下格式的 XML 格式
I have an XML format with following format
<Tag>
Value
</Tag>
這來(lái)自我無(wú)法更改的外部數(shù)據(jù)源.使用 XmlReader
時(shí),內(nèi)容有 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?
推薦答案
答案無(wú)效
這個(gè)答案似乎不起作用,但我暫時(shí)離開(kāi)它以避免其他人建議它.如果有人發(fā)布更好的答案,我會(huì)刪除它.
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.
您是否嘗試設(shè)置 XmlReaderSettings.IgnoreWhitespace
?
Did you try setting XmlReaderSettings.IgnoreWhitespace
?
不重要的空白包括用于分隔標(biāo)記以提高可讀性的空格、制表符和空行.元素內(nèi)容中的空白就是一個(gè)例子.
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.
由于某種原因,這不會(huì)影響 ReadElementContentAsString
甚至是文本節(jié)點(diǎn)的 Value
屬性.
For some reason this doesn't affect ReadElementContentAsString
or even the Value
property of a text node.
簡(jiǎn)單回答
你可以調(diào)用 Trim
:
string value = reader.ReadElementContentAsString().Trim();
這不會(huì)刪除 內(nèi)容行之間的換行符,當(dāng)然...如果您需要這樣做,您可以隨時(shí)使用 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
.
(正如我在評(píng)論中提到的,我個(gè)人更喜歡使用 LINQ to XML 而不是 XmlReader
除非你真的在閱讀太大而無(wú)法放入內(nèi)存的東西,但這是另一回事.)
(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.)
這篇關(guān)于讀取 XML 時(shí)忽略空格的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!