【问题标题】:How create XElement with specific namespace?如何创建具有特定命名空间的 XElement?
【发布时间】:2012-08-21 07:24:13
【问题描述】:

我在 LinqToXml 中创建新元素时遇到问题。 这是我的代码:

XNamespace xNam = "name"; 
XNamespace _schemaInstanceNamespace = @"http://www.w3.org/2001/XMLSchema-instance";

XElement orderElement = new XElement(xNam + "Example",
                  new XAttribute(XNamespace.Xmlns + "xsi", _schemaInstanceNamespace));

我想得到这个:

<name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

但在 XML 中我总是得到这个:

<Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="name">

我做错了什么?

【问题讨论】:

  • 这就是你需要的stackoverflow.com/a/4986019/570150
  • V4Vendetta:这是类似的问题,但现在我得到了这个:&lt;name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:name="name"&gt;

标签: c# .net xml linq-to-xml


【解决方案1】:

&lt;name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; 不是格式良好的命名空间,因为前缀 name 未声明。因此,无法使用 XML API 构建它。您可以做的是构造以下命名空间格式良好的 XML

<name:Example xmlns:name="http://example.com/name" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />

用代码

//<name:Example xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:name="http://example.com/name"></name:Example>

XNamespace name = "http://example.com/name";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

XElement example = new XElement(name + "Example",
new XAttribute(XNamespace.Xmlns + "name", name),
new XAttribute(XNamespace.Xmlns + "xsi", xsi));

Console.WriteLine(example);

【讨论】:

  • 我忘记写这个了。命名空间名称在父节点中声明。创建 xml 后,我总是在一些 xml 验证器上验证它。
猜你喜欢
  • 2023-03-14
  • 2021-08-08
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多