[英]How to specify an xmlns for XDocument?
我试过了:
textBox1.Text = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
new XElement("root1", new XAttribute( "xmlns", @"http://example.com"), new XElement("a", "b"))
).ToString();
但我得到:
The prefix '' cannot be redefined from '' to 'http://example.com' within the same start element tag.
我也试过替换(根据我发现的答案):
XAttribute(XNamespace.Xmlns,...
但也有错误。
注意 :我不是要在文档中使用多个xmlns。
XDocument
API与命名空间范围名称一起使用的方式是XName
实例。 只要您接受XML名称不仅仅是字符串,而是作用域标识符,这些都非常容易使用。 我是这样做的:
var ns = XNamespace.Get("http://example.com");
var doc = new XDocument(new XDeclaration("1.0", "utf-8", null));
var root = new XElement(ns + "root1", new XElement(ns + "a", "b"));
doc.Add(root);
结果:
<root1 xmlns="http://example.com">
<a>b</a>
</root1>
请注意, +
运算符被重载以接受XNamespace
和String
以XName
和XName
实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.