我曾經不止一次(當然不僅僅是我意識到這個問題)說到過,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();
}
}
}
不太難,但是確實是多了些步驟,不是嗎