Max*_*Max 9 c# xml-serialization
使用代码序列化对象时:
var xmlSerializer = new XmlSerializer(typeof(MyType));
using (var xmlWriter = new StreamWriter(outputFileName))
{
xmlSerializer.Serialize(xmlWriter, myTypeInstance);
}
Run Code Online (Sandbox Code Playgroud)
在输出xml文件中,我得到:
<MyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
Run Code Online (Sandbox Code Playgroud)
如何向其添加对xml架构的引用,因此它看起来像这样:
<MyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xsi:noNamespaceSchemaLocation="mySchema.xsd">
Run Code Online (Sandbox Code Playgroud)
Ste*_* K. 16
[编辑]
您可以显式实现IXmlSerializable并自己编写/读取xml.
public class MyType : IXmlSerializable
{
void IXmlSerializable.WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
writer.WriteAttributeString("xsi", "noNamespaceSchemaLocation", XmlSchema.InstanceNamespace, "mySchema.xsd");
// other elements & attributes
}
XmlSchema IXmlSerializable.GetSchema()
{
throw new NotImplementedException();
}
void IXmlSerializable.ReadXml(XmlReader reader)
{
throw new NotImplementedException();
}
}
xmlSerializer.Serialize(xmlWriter, myTypeInstance);
Run Code Online (Sandbox Code Playgroud)
很可能不是一个理想的解决方案,但在您的课程中添加以下字段和属性将起到作用.
public class MyType
{
[XmlAttribute(AttributeName="noNamespaceSchemaLocation", Namespace="http://www.w3.org/2001/XMLSchema-instance")]
public string Schema = @"mySchema.xsd";
}
Run Code Online (Sandbox Code Playgroud)
另一个选择是创建自己的自定义XmlTextWriter类.
xmlSerializer.Serialize(new CustomXmlTextWriter(xmlWriter), myTypeInstance);
Run Code Online (Sandbox Code Playgroud)
或者不要使用序列化
var xmlDoc = new XmlDocument();
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null));
var xmlNode = xmlDoc.CreateElement("MyType");
xmlDoc.AppendChild(xmlNode);
xmlNode.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
xmlNode.SetAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
var schema = xmlDoc.CreateAttribute("xsi", "noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
schema.Value = "mySchema.xsd";
xmlNode.SetAttributeNode(schema);
xmlDoc.Save(...);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助...
| 归档时间: |
|
| 查看次数: |
10813 次 |
| 最近记录: |