我曾经不止一次(当然不仅仅是我意识到这个问题)说到过,XML标准中的Namespace的设计其实是一个较为失败的设计,它有它的优点,但缺点更多。
http://zzk.cnblogs.com/s?w=blog%3Achenxizhang+xml+%E5%91%BD%E5%90%8D%E7%A9%BA%E9%97%B4&t=
这里又有一个范例。我们需要在XML序列化的时候,更加小心地注意namespace的问题。
下面有一个例子程序
-
数据实体模型(这个类是通过xsd工具自动生成的,具体用途这里就不做展开了
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.0.30319.33440.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://schemas.microsoft.com/office/infopath/2003/myXSD/2014-08-15T22:37:24")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="http://schemas.microsoft.com/office/infopath/2003/myXSD/2014-08-15T22:37:24", IsNullable=false)]
public partial class myFields {
private string titleField;
private System.Xml.XmlAttribute[] anyAttrField;
/// <remarks/>
public string Title {
get {
return this.titleField;
}
set {
this.titleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAnyAttributeAttribute()]
public System.Xml.XmlAttribute[] AnyAttr {
get {
return this.anyAttrField;
}
set {
this.anyAttrField = value;
}
}
}
-
实际对应的XML文档应该是下面这样的。注意,下面有一个my的命名空间。
<?xml version="1.0" encoding="UTF-8"?><?mso-infoPathSolution solutionVersion="1.0.0.3" productVersion="15.0.0" PIVersion="1.0.0.0" href="file:///C:\Users\chenxizhang\AppData\Local\Microsoft\InfoPath\Designer4\46fec1056ed24f25\manifest.xsf" ?><?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.4"?><my:myFields xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2014-08-15T22:37:24" xml:lang="en-us">
<my:Title>test</my:Title>
</my:myFields>
-
为了使得XML序列化的时候,正常地生成这样的一份文档。我们需要做如下的特殊设计
using System;
using System.IO;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//1.准备数据
var data = new myFields() { Title = "CEO" };
//2.准备命名空间
var ns = new XmlSerializerNamespaces();
ns.Add("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2014-08-15T22:37:24");
//3.准备序列化器
var serializer = new XmlSerializer(typeof(myFields));
//4.准备用来接收的内存流
var ms = new MemoryStream();
//5.执行序列化
serializer.Serialize(ms, data, ns);
//6.将内容读取出来
var reader = new StreamReader(ms);
ms.Position = 0;
Console.WriteLine(reader.ReadToEnd());
//7.关闭流
reader.Close();
ms.Close();
Console.Read();
}
}
}
不太难,但是确实是多了些步骤,不是吗