如何使用XElement的命名空间和前缀编写xml?
问题描述:
这可能是一个初学XML问题,但我怎样才能生成一个如下所示的XML文档?如何使用XElement的命名空间和前缀编写xml?
<root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com">
<ci:field1>test</ci:field1>
<ca:field2>another test</ca:field2>
</root>
如果我能得到这个写,我能得到我的问题的其他工作。理想情况下,我希望使用LINQ to XML(XElement,XNamespace等)与c#,但如果这可以通过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"));
}
}
答
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);
Th是应该输出
<root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com">
<ci:field1>test</ci:field1>
<ca:field2>another test</ca:field2>
</root>
答
对于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);
答
试试这个代码:
string prefix = element.GetPrefixOfNamespace(element.Name.NamespaceName);
string name = String.Format(prefix == null ? "{1}" : "{0}:{1}", prefix, element.Name.LocalName);`
你不需要在那里为冒号工作?另外,不''XNamespace.Xmlns'输出'http:// www.w3.org/2000/xmlns /'? – 2016-04-14 18:06:10
@ BrainStorm.exe否如最初所回答的,代码按预期工作。当XNamespace添加字符串时,冒号会自动添加进来。这不是必须手动执行的。 – techvice 2016-05-11 19:00:47
这是[详细说明XNamespace和字符串的添加运算符的文档](https://msdn.microsoft.com/en-us/library/system.xml.linq.xnamespace.op_addition(v = vs.110)。 ASPX) – techvice 2016-05-11 19:15:45