2014-09-25 120 views
-1

我必须从代​​码生成特定的XML数据。 的XML需要看起来像这样从C#生成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涉猎,但无法得到的输出匹配这个正是

请帮助。

+0

你究竟试过了什么?你能分享你的努力的一些代码,并指出究竟出了什么问题吗? – 2014-09-25 16:07:50

回答

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()); 
     }