C# 如何编写带有名称空间和前缀XElement的xml?
这可能是一个xml初学者的问题,但如何生成如下所示的xml文档C# 如何编写带有名称空间和前缀XElement的xml?,c#,xml,linq-to-xml,C#,Xml,Linq To Xml,这可能是一个xml初学者的问题,但如何生成如下所示的xml文档 <root xmlns:ci="http://somewhere.com" xmlns:ca="http://somewhereelse.com"> <ci:field1>test</ci:field1> <ca:field2>another test</ca:field2> </root> 测试 另一个测试 如果我能把这个写下来,我就能把
<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"));
}
}
这应该是输出
<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
outputhttp://www.w3.org/2000/xmlns/
?@BrainStorm.exe否。正如最初的回答,代码按预期工作。当XNamespace与字符串一起添加时,冒号将自动添加到中。这不是必须手动执行的操作
string prefix = element.GetPrefixOfNamespace(element.Name.NamespaceName);
string name = String.Format(prefix == null ? "{1}" : "{0}:{1}", prefix, element.Name.LocalName);`