简体   繁体   English

XmlTextWriter将对象序列化为XML元素

[英]XmlTextWriter serialize Object to XML element

I would like to perform object serialization to only one branch in an existing XML file. 我想对现有XML文件中的一个分支执行对象序列化。 While reading by using: 阅读时使用:

        RiskConfiguration AnObject;

        XmlSerializer Xml_Serializer = new XmlSerializer(typeof(RiskConfiguration));
        XmlTextReader XmlReader = new XmlTextReader(@"d:\Projects\RiskService\WCFRiskService\Web.config");
        XmlReader.ReadToDescendant("RiskConfiguration");
        try
        {
            AnObject = (RiskConfiguration)Xml_Serializer.Deserialize(XmlReader);
            AnObject.Databases.Database[0].name = "NewName";
        }
        finally
        {
            XmlReader.Close();
        }

It is possible, I do not know how to edit the object again performed it can save the file without erasing other existing elements in an XML file. 有可能,我不知道如何再次编辑对象,它可以保存文件而不删除XML文件中的其他现有元素。 Can anyone help me? 谁能帮我?

I found a way to display the desired item serialization. 我找到了一种显示所需项目序列化的方法。 How do I go now instead of the paste to the original element in XML? 我现在该怎么做而不是粘贴到XML中的原始元素?

        StringWriter wr = new StringWriter();
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.OmitXmlDeclaration = true;
        settings.Encoding = System.Text.Encoding.Default;

        using (XmlWriter writer = XmlWriter.Create(wr, settings))
        {
            XmlSerializerNamespaces emptyNamespace = new XmlSerializerNamespaces();
            emptyNamespace.Add(String.Empty, String.Empty);
            Xml_Serializer.Serialize(writer, AnObject, emptyNamespace);
            MessageBox.Show(wr.ToString());
        }

First of all, you should stop using new XmlTextReader() . 首先,您应该停止使用new XmlTextReader() That has been deprecated since .NET 2.0. 自.NET 2.0以来,这已被弃用。 Use XmlReader.Create() instead. 请改用XmlReader.Create()

Second, XML is not a random-access medium. 其次,XML不是随机访问媒体。 You can't move forward and backwards, writing into the middle of the file. 你不能向前和向后移动,写入文件的中间。 It's a text-based file. 这是一个基于文本的文件。

If you need to "modify" the file, then you'll need to write a new version of the file. 如果您需要“修改”该文件,则需要编写该文件的新版本。 You could read from the original file, up to the point where you need to deserialize, writing the nodes out to a new version of the file. 您可以从原始文件中读取,直到您需要反序列化的程度,将节点写入文件的新版本。 You could then deserialize from the original file, modify the objects, and serialize out to the new version. 然后,您可以从原始文件反序列化,修改对象,并序列化为新版本。 You could then continue reading from the original and writing the nodes out to the new version. 然后,您可以继续从原始读取并将节点写入新版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM