[英]C# XmlSerializer trim whitespaces
I've trouble trimming strings when using the XmlSerializer
, when using a XmlReader. 使用
XmlSerializer
和XmlReader时,我无法修剪字符串。 The IgnoreWhitespace option shows no effect and the element string still contains \\n and whitespaces. IgnoreWhitespace选项不显示任何效果,并且元素字符串仍然包含\\ n和空格。
Is there any way to trim it "on the fly"? 有没有办法“即时”修剪它? I would prefer such a method since I deserialize into an array of strings
我更喜欢这种方法,因为我反序列化为字符串数组
Here's an example xml: 这是一个示例xml:
<?xml version='1.0' encoding='UTF-8'?>
<root>
<element>
some random string
</element>
<element>
another random string
</element>
</root>"
And here's the example code: 这是示例代码:
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; }
}
After reading in the XML file, you need to manually trim out the whitespace 读完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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.