如何使用命名空间和XElement前缀编写xml?

这可能是一个初学者xml问题,但是如何生成如下所示的xml文档呢?

 test another test  

如果我可以写这个,我可以解决我的其余问题。

理想情况下,我想用c#使用LINQ to XML(XElement,XNamespace等),但如果使用XmlDocuments和XmlElements可以更容易/更好地实现这一点,我会继续使用它。

谢谢!!!

这是一个创建所需输出的小示例:

 using System; using System.Xml.Linq; class Program { static void Main() { XNamespace ci = "http://somewhere.com"; XNamespace ca = "http://somewhereelse.com"; XElement element = new XElement("root", new XAttribute(XNamespace.Xmlns + "ci", ci), new XAttribute(XNamespace.Xmlns + "ca", ca), new XElement(ci + "field1", "test"), new XElement(ca + "field2", "another test")); } } 

试试这段代码:

 string prefix = element.GetPrefixOfNamespace(element.Name.NamespaceName); string name = String.Format(prefix == null ? "{1}" : "{0}:{1}", prefix, element.Name.LocalName);` 

我希望你能从这个线程中获得一些有用的信息 – 属性上的XElement默认命名空间提供了意想不到的行为

编辑:

另一个常见问题解答 – http://social.msdn.microsoft.com/Forums/en-US/xmlandnetfx/thread/c0648840-e389-49be-a3d2-4d5db17b8ddd

 XNamespace ci = "http://somewhere.com"; XNamespace ca = "http://somewhereelse.com"; XElement root = new XElement(aw + "root", new XAttribute(XNamespace.Xmlns + "ci", "http://somewhere.com"), new XAttribute(XNamespace.Xmlns + "ca", "http://somewhereelse.com"), new XElement(ci + "field1", "test"), new XElement(ca + "field2", "another test") ); Console.WriteLine(root); 

这应该输出

  test another test  

对于XmlDocument,它是类似的:

 XmlAttribute attribute1 = sessionXml.CreateAttribute("s", "Attribute1", namespaceURI); XmlAttribute attribute2 = sessionXml.CreateAttribute("s", "Attribute2", namespaceURI); XmlAttribute attribute3 = sessionXml.CreateAttribute("s", "Attribute3", namespaceURI); XmlAttribute attribute4 = sessionXml.CreateAttribute("s", "Attribute4", namespaceURI);