从C#代码生成XML

时间:2014-09-25 16:05:59

标签: c# xml xml-serialization

我必须从代​​码生成特定的XML数据。 XML需要看起来像这样

<this:declarationIdentifier xmlns:this="demo.org.uk/demo/DeclarationGbIdentifier"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="demo.org.uk/demo/DeclarationGbIdentifier DeclarationGbIdentifier.xsd"
xmlns:nsIdentity="demo.org.uk/demo/DeclarationGbIdentityType">
<this:declarationIdentity>
<nsIdentity:declarationUcr>Hello World</nsIdentity:declarationUcr>
</this:declarationIdentity>
</this:declarationIdentifier>

我已经涉足了XmlSerializer和XDocument但是无法让输出完全匹配

请帮忙。

1 个答案:

答案 0 :(得分:1)

我相信这会产生你想要的输出。可能有一种更简单的方法,这只是让你开始的袖口。使用您需要的前缀,我会查找XmlDocument并向其添加名称空间,以便更好地理解下面的代码正在做什么。我还要做的是尝试获取XSD架构文件并使用XSD.exe构建.cs文件,然后您可以继续使用XmlSerializer。如果您继续使用下面的代码,我强烈建议您将您的namespaceuri转移到一些软设置文件中,这样您就可以在它们发生变化时轻松修改它们。

        XmlDocument doc = new XmlDocument();

        XmlElement root = doc.CreateElement("this", "declarationIdentifier", "demo.org.uk/demo/DeclarationGbIdentifier");
        root.SetAttribute("xmlns:this", "demo.org.uk/demo/DeclarationGbIdentifier");
        root.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

        //Just setting an Attribute of xsi:schemaLocation it would always drop the xsi prefix in the xml so this is different to accomodate that
        XmlAttribute schemaAtt = doc.CreateAttribute("xsi", "schemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
        schemaAtt.Value = "demo.org.uk/demo/DeclarationGbIdentifier DeclarationGbIdentifier.xsd";
        root.Attributes.Append(schemaAtt);

        root.SetAttribute("xmlns:nsIdentity", "demo.org.uk/demo/DeclarationGbIdentityType");
        doc.AppendChild(root);

        XmlElement declarationIdentity = doc.CreateElement("this", "declarationIdentity", "demo.org.uk/demo/DeclarationGbIdentifier");

        XmlElement declarationUcr = doc.CreateElement("nsIdentity","declarationUcr","demo.org.uk/demo/DeclarationGbIdentityType");
        declarationUcr.InnerText = "Hello World";
        declarationIdentity.AppendChild(declarationUcr);

        doc.DocumentElement.AppendChild(declarationIdentity);

要将其作为字符串输出或将其转储到文件中,您可以使用以下操作,我输出到文件以及输出到我的测试应用程序中的控制台。

        using (var stringWriter = new StringWriter())
        using (StreamWriter writer = new StreamWriter(@"C:\<Path to File>\testing.xml"))
        using (var xmlTextWriter = XmlWriter.Create(stringWriter))
        {
            doc.WriteTo(xmlTextWriter);
            xmlTextWriter.Flush();
            writer.Write(stringWriter.GetStringBuilder().ToString());
            Console.WriteLine(stringWriter.GetStringBuilder().ToString());
        }