2012-07-19 14 views
2

我想提供一种方法来保存应用程序中的工作。这是一种项目功能。这些项目需要序列化为XML。我有DataContractSerializer生成XML,但我需要能够选择XML文件中的一个位置,以便序列化为一个位置,而不是为自己编写一个完整的文件,因为会有多个项目,我需要能够从项目XML文件中分别对这些项目进行序列化/序列化。DataContractSerializer序列化到特定的XML节点

我想为XML内容:

<Projects> 
    <Project> 
     <ID>...</ID> 
     <Name>...</Name> 
     <LastEdited>...</LastEdited> 
     ... 
    </Project> 
    <Project>...</Project> 
    <Project>...</Project> 
</Projects> 

然后我会根据使用LINQ to XML来浏览文档,项目编号序列化和反序列化。

有什么建议吗?非常感谢提前。

回答

1

找到了一种方法来做到这一点。它有它的结果,但一旦你把所有的东西都包括进来,它的工作非常顺利。

要生成的XML:

DataContractSerializer ser = new DataContractSerializer(typeof(Project)); 
StringBuilder objectSB = new StringBuilder(); 
XmlWriter objectWriter = XmlWriter.Create(objectSB); 
//I'm using this method in the object I want to serialize (hence the 'this') 
ser.WriteObject(objectWriter, this); 
objectWriter.Flush(); 

然后你就可以把StringBuilder的成Linq的一个的XElement为XML:

Xelement xProject = Xelement.Parse(objectSB.ToString()); 

反序列化:

DataContractSerializer ser = new DataContractSerializer(typeof(Project)); 
Project project = (CoilProject)ser.ReadObject(xProject.CreateReader()); 

有有几次我使用Linq to XML编辑XML而没有反序列化和重新序列化。由于该DataContractSerializer的增加了命名空间,这成为必要:

//place this somewhere in your project's namespace 
public static class MyExtensions 
{ 
    public static IEnumerable<XElement> ElementsAnyNS(this XElement source, string localName) 
    { 
     return source.Elements().Where(e => e.Name.LocalName == localName); 
    } 

    public static XElement ElementAnyNS(this XElement source, string localName) 
    { 
     return source.Elements().Where(e => e.Name.LocalName == localName).Select(e => e).Single(); 
    } 
} 

这些扩展方法可以让你选择从序列化对象的一个​​或多个元素,而不必担心命名空间。我改编了Pavel Minaev's answer上的这些扩展方法Ignore namespaces in LINQ to XML