Dev*_*ble 3 c# xml xml-serialization xmlserializer
我需要在序列化期间生成以下XML :(片段)
<IncidentEvent a:EventTypeText="Beginning" xmlns:a="http://foo">
<EventDate>2013-12-18</EventDate>
<EventTime>00:15:28</EventTime>
</IncidentEvent>
Run Code Online (Sandbox Code Playgroud)
有问题的类看起来像这样:
public class IncidentEvent
{
public string EventDate { get; set; }
public string EventTime { get; set; }
[XmlAttribute("EventTypeText", Namespace = "http://foo")]
public string EventTypeText { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
似乎序列化程序注意到命名空间已经在xmlns:root中声明,并且忽略了我的属性.我也尝试过以下方法:
[XmlRoot(Namespace = "http://foo")]
public class IncidentEvent
{
public string EventDate { get; set; }
public string EventTime { get; set; }
private XmlSerializerNamespaces _Xmlns;
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Xmlns
{
get
{
if (_Xmlns == null)
{
_Xmlns = new XmlSerializerNamespaces();
_Xmlns.Add("ett", "http://foo");
}
return _Xmlns;
}
set
{
_Xmlns = value;
}
}
[XmlAttribute("EventTypeText", Namespace = "http://foo")]
public string EventTypeText { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这导致以下XML:
<ett:IncidentEvent EventTypeText="Beginning" xmlns:ett="http://foo">
<ett:EventDate>2013-12-18</ett:EventDate>
<ett:EventTime>00:15:28</ett:EventTime>
</ett:IncidentEvent>
Run Code Online (Sandbox Code Playgroud)
这不是我想要的.元素不应该是前缀,属性应该是.需要什么才能让序列化程序了解我想要的内容?
这可能是一个错误XmlSerializer.
正如您所注意到的,即使XmlAttributeAttribute.Namespace明确设置,该属性也不会在某些情况下作为前缀.从测试开始,这似乎发生在属性名称空间恰好与当前正在编写的元素的名称空间相同时.
例如:
[XmlRoot(Namespace = "http://foo")]
public class IncidentEvent
{
[XmlAttribute("EventTypeText", Namespace = "http://foo")]
public string EventTypeText { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
序列化为以下XML:
Run Code Online (Sandbox Code Playgroud)<q1:IncidentEvent EventTypeText="an attribute" xmlns:q1="http://foo" />
由于该属性没有前缀,因此它实际上不在任何名称空间中,如XML标准中所述:未加前缀的属性名称的名称空间名称始终没有值.
但是,以下内容:
[XmlRoot(Namespace = "http://foo")]
public class IncidentEvent
{
[XmlAttribute("EventTypeText", Namespace = "http://bar")]
public string EventTypeText { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
使用正确的前缀属性进行序列化:
Run Code Online (Sandbox Code Playgroud)<q1:IncidentEvent p1:EventTypeText="an attribute" xmlns:p1="http://bar" xmlns:q1="http://foo" />
解决方法是明确设置[XmlAttribute(Form = XmlSchemaForm.Qualified)].从而:
[XmlRoot(Namespace = "http://foo")]
public class IncidentEvent
{
[XmlAttribute("EventTypeText", Namespace = "http://foo", Form = XmlSchemaForm.Qualified)]
public string EventTypeText { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
序列化为
Run Code Online (Sandbox Code Playgroud)<q1:IncidentEvent q1:EventTypeText="an attribute" xmlns:q1="http://foo" />
按要求.