我试过:
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。
发布于 2013-02-12 20:10:18
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>注意,+操作符被重载,以接受要生成和XName实例的XNamespace和String。
https://stackoverflow.com/questions/14840723
复制相似问题