【问题标题】:Append Serialized Object Into XML in C#在 C# 中将序列化对象附加到 XML 中
【发布时间】:2016-10-19 17:38:06
【问题描述】:

我有一个这样的 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 示例)

【问题讨论】:

  • 请提供您尝试过的代码。
  • 感谢您的关注。我解决了它,它工作正常。

标签: c# xml serialization


【解决方案1】:

我解决了这个问题。使用代码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);

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    相关资源
    最近更新 更多