是的,您可以告诉XmlSerializer在反序列化期间忽略名称空间。
定义一个XmlTextReader忽略名称空间。像这样:
// helper class to ignore namespaces when de-serializingpublic class NamespaceIgnorantXmlTextReader : XmlTextReader{ public NamespaceIgnorantXmlTextReader(System.IO.TextReader reader): base(reader) { } public override string NamespaceURI { get { return ""; } }}// helper class to omit XML decl at start of document when serializingpublic class XTWFND : XmlTextWriter { public XTWFND (System.IO.TextWriter w) : base(w) { Formatting= System.Xml.Formatting.Indented;} public override void WriteStartdocument () { }}
这是一个示例,说明如何使用该TextReader反序列化:
public class MyType1 { public string Label { set { _Label= value; } get { return _Label; } } private int _Epoch; public int Epoch { set { _Epoch= value; } get { return _Epoch; } } } String RawXml_WithNamespaces = @" <MyType1 xmlns='urn:booboo-dee-doo'> <Label>This document has namespaces on its elements</Label> <Epoch xmlns='urn:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'>0</Epoch> </MyType1>"; System.IO.StringReader sr; sr= new System.IO.StringReader(RawXml_WithNamespaces); var o1= (MyType1) s1.Deserialize(new NamespaceIgnorantXmlTextReader(sr)); System.Console.WriteLine("nnDe-serialized, then serialized again:n"); s1.Serialize(new XTWFND(System.Console.Out), o1, ns); Console.WriteLine("nn");
结果是这样的:
<MyType1> <Label>This document has namespaces on its elements</Label> <Epoch>0</Epoch> </MyType1>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)