Xml Serializer-顶级元素上的默认名称空间 [英] Xml Serializer - Default namespace on top-level Element
问题描述
我使用XmlSerializer,我正在寻找一种在顶层Element上设置默认XML名称空间的方法.我希望正确的方法是在顶级类的XmlType属性中指定此方法.但是,名称空间仅适用于此类的子级.例如,请参见下面的C#代码,它序列化了一个简单的嵌套结构:
Hi,
I use the XmlSerializer and I''m looking for a way to set the default XML namespace on the top level Element. The correct way to do this, I hoped, was to specify this in an XmlType attribibute on the top level class. However, the namespace is only applied to the children of this class. For example, see the C# code below that serializes a simple nested structure:
// Contained class.<br /> public class Circle<br /> {<br /> }<br /><br /> // Container class.<br /> [XmlType(Namespace="http://mbshapes.com")] // Why does the Shapes element not use this namespace?<br /> public class Shapes<br /> {<br /> private Circle _circle = new Circle();<br /><br /> public Circle Circle<br /> {<br /> get<br /> {<br /> return _circle;<br /> }<br /> set<br /> {<br /> _circle = value;<br /> }<br /> }<br /> }<br /><br /> // Serialize Shapes object.<br /> public class SerializeTest<br /> {<br /> public static void Serialize()<br /> {<br /> // Create Shapes object.<br /> Shapes shapes = new Shapes();<br /><br /> // Open file.<br /> using (TextWriter textWriter = new StreamWriter("Shapes.xml"))<br /> { <br /> // Serialize.<br /> XmlSerializer xmlSerializer = new XmlSerializer(typeof(Shapes));<br /> xmlSerializer.Serialize(textWriter, shapes);<br /> }<br /> }<br /> }
输出是这样的:
The output is this:
<?xml version="1.0" encoding="utf-8"?><br /><Shapes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><br /> <Circle xmlns="http://mbshapes.com" /><br /></Shapes>
我所期望的(以及我所需要的)是这样的:
What I expected (and what I need), is something like this:
<br /><?xml version="1.0" encoding="utf-8"?><br /><Shapes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://mbshapes.com"><br /> <Circle /><br /></Shapes><br />
我做错了什么吗?还是有任何解决方法?
谢谢.
Am I doing something wrong? Or are there any work-arounds?
Thanks.
推荐答案
尝试
[<code>XmlRoot</code>(Namespace = "http://mbshapes.com")]<br /> public class Shapes<br /> {<br /> private Circle _circle = new Circle();<br /><br /> public Circle Circle<br /> {<br /> get<br /> {<br /> return _circle;<br /> }<br /> set<br /> {<br /> _circle = value;<br /> }<br /> }<br /> }
这篇关于Xml Serializer-顶级元素上的默认名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!