在C#中将序列化对象附加到XML中

时间:2016-10-19 09:09:20

标签: c# xml serialization

我有像这样的XML结构

<?xml version="1.0" encoding="utf-8"?>
<Product>
  <ProductName>da</ProductName>
  <PluginPath></PluginPath>
  <Instances></Instances>
</Product>

我将我的对象序列化为字符串。

<?xml version="1.0"?>
<Instance xmlns:xsi="http://bla bla" xmlns:xsd="bla bla" UniqueId="d4820029b7d7">
<InstanceName>Instance MyTestPluginForm</InstanceName>
<Description>Test Plugin IW</Description>
<AddedDate>2016-10-19T11:05:10.7443404+02:00</AddedDate>
<LogSettings>
<LoggingLevel>None</LoggingLevel>
<LogFilePath /><MaximumSize>100</MaximumSize
<ClearAfterDays>7</ClearAfterDays>
<IsSaveActiviesToEventLog>false</IsSaveActiviesToEventLog>
</LogSettings>
<ProductSpecific/>
</Instance>

所以我想在第一个xml的Instances节点中追加第二个。但是正如你所看到的那样,两者都有xml定义,并且在序列化之后我得到了xmlns:xsi和xmlns:xsd属性。

如何解决这个问题?

PS:我不想创建XML元素。因为我的xml架构是动态的。它必须通过序列化完成。 (我已经检查了this样本)

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。使用代码here

    public static void CreateXmlFile(Instance instance, string filePath)
    {

       var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Product><ProductName>da</ProductName><PluginPath></PluginPath><Instances></Instances></Product>";



        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(xml);
        xmlDocument.Save(filePath);


        XmlNode xnode = xmlDocument.CreateNode(XmlNodeType.Element, "Instances", null);
        XmlSerializer xSeriz = new XmlSerializer(typeof(Instance));
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("", "");
        XmlWriterSettings writtersetting = new XmlWriterSettings();
        writtersetting.OmitXmlDeclaration = true;
        StringWriter stringwriter = new StringWriter();
        using (XmlWriter xmlwriter = System.Xml.XmlWriter.Create(stringwriter, writtersetting))
        {
            xSeriz.Serialize(xmlwriter, instance, ns);
        }
        xnode.InnerXml = stringwriter.ToString();
        XmlNode bindxnode = xnode.SelectSingleNode("Instance");
        xmlDocument.DocumentElement.SelectSingleNode("Instances").AppendChild(bindxnode);
        xmlDocument.Save(filePath);

    }