我相信这会产生你想要的输出。这可能是一种更简单的方式,只是为了让你开始。使用你所需要的前缀,我会查找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());
}
你究竟试过了什么?你能分享你的努力的一些代码,并指出究竟出了什么问题吗? – 2014-09-25 16:07:50