例如,我如何在 C# 中生成这个 XML
<?xml version='1.0'?>
<oneshot xmlns='http://www.w3.org/2002/xforms' xmlns:dm='http://mobileforms.foo.com/xforms' xmlns:h='http://www.w3.org/1999/xhtml' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<dm:form_namespace>Foo</dm:form_namespace>
<Days>6</Days>
<Leave_Type>Option 3</Leave_Type>
</oneshot>
我特别纠结于 xmlns:dm 声明。有什么想法吗?
最佳答案
您最好的选择(阅读:最少的黑客攻击)可能是自定义 IXmlSerializable
实现;您可以部分通过 XmlRootAttribute
、XmlElementAttribute
等的组合获得您想要的内容,如下所示:
[Serializable]
[XmlRoot("oneshot")]
public class OneShot
{
[XmlElement("form_namespace", Namespace="http://mobileforms.foo.com/xforms")]
public string FormNamespace {get; set;}
[XmlElement("Days")]
public int Days {get; set;}
[XmlElement("Leave_Type")]
public string LeaveType {get; set;}
这将生成如下内容:
<?xml version="1.0" encoding="utf-16"?>
<oneshot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<form_namespace xmlns="http://mobileforms.foo.com/xforms">Foo</form_namespace>
<Days>6</Days>
<Leave_Type>Option 3</Leave_Type>
</oneshot>
但是如果你实现了IXmlSerializable
,你就拥有了完全的控制权:
public class OneShot : IXmlSerializable
{
public string FormNamespace {get; set;}
public int Days {get; set;}
public string LeaveType {get; set;}
#region IXmlSerializable
public void WriteXml (XmlWriter writer)
{
writer.WriteStartElement("oneshot");
writer.WriteAttributeString("xmlns", null, "http://www.w3.org/2002/xforms");
writer.WriteAttributeString("xmlns:dm", null, "http://mobileforms.foo.com/xforms");
writer.WriteAttributeString("xmlns:h", null, "http://www.w3.org/1999/xhtml");
writer.WriteAttributeString("xmlns:xsd", null, "http://www.w3.org/2001/XMLSchema");
writer.WriteElementString("dm:form_namespace", null, FormNamespace);
writer.WriteElementString("Days", Days.ToString());
writer.WriteElementString("Leave_Type", LeaveType);
writer.WriteEndElement();
}
public void ReadXml (XmlReader reader)
{
// populate from xml blob
}
public XmlSchema GetSchema()
{
return(null);
}
#endregion
}
这给了你:
<?xml version="1.0" encoding="utf-16"?>
<OneShot>
<oneshot xmlns="http://www.w3.org/2002/xforms" xmlns:dm="http://mobileforms.foo.com/xforms" xmlns:h="http://www.w3.org/1999/xhtml" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<dm:form_namespace>Foo</dm:form_namespace>
<Days>6</Days>
<Leave_Type>Option 3</Leave_Type>
</oneshot>
</OneShot>
关于c# - 如何在 C# 中创建具有多个命名空间属性的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14991959/