使用XmlReader时,在使用XmlSerializer
时修剪字符串时遇到了麻烦。 IgnoreWhitespace选项显示无效,元素字符串仍包含\ n和空格。
有没有办法修剪它"在飞行中"? 我更喜欢这样的方法,因为我反序列化为字符串数组
这是一个例子xml:
<?xml version='1.0' encoding='UTF-8'?>
<root>
<element>
some random string
</element>
<element>
another random string
</element>
</root>"
以下是示例代码:
class Program
{
public static void Main(string[] args)
{
string xml =
@"<?xml version='1.0' encoding='UTF-8'?>
<root>
<element>
some random string
</element>
<element>
another random string
</element>
</root>";
var string_reader = new StringReader(xml);
var xml_reader = XmlReader.Create(string_reader, new XmlReaderSettings()
{
IgnoreWhitespace = true //setting this option doesn't work
});
root d = (root)new XmlSerializer(typeof(root)).Deserialize(xml_reader);
d.elements[0].Contains("\n"); //true
//Dispose string/xml reader
Console.Read();
}
}
public class root
{
[XmlElement(ElementName ="element")]
public string[] elements { set; get; }
}
答案 0 :(得分:3)
在读取XML文件后,您需要手动修剪空白
root d = (root)new XmlSerializer(typeof(root)).Deserialize(xml_reader);
for (int i = 0; i < d.elements.Count; i++)
{
d.elements[i] = d.elements[i].Replace("\n", String.Empty).Trim();
}