使用命名空间创建 XElement?

Creating XElement with namespaces?

我正在尝试进入以下 XML(对于第 3 方;因此需要准确)并且在内部元素的 xmlns 方面遇到一些问题:

<headerResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <sessionID xmlns="http://www.example.com/portal-api">4654654564</sessionID>
  <uniqueTranID xmlns="http://www.example.com/portal-api">gh0000000</uniqueTranID>
  <statusCode xmlns="http://www.example.com/portal-api">1</statusCode>
  <statusCodeDescription xmlns="http://www.example.com/portal-api">jhkjhkjhkjhkjkjhkjkkjhkhk</statusCodeDescription>
  <message xmlns="http://www.example.com/portal-api">testMessage</message>
</headerResponse>

从其他示例中,我得到以下内容:

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

XElement example = new XElement("headerResponse",
  new XAttribute(XNamespace.Xmlns + "xsi", xsi),
  new XAttribute(XNamespace.Xmlns + "xsd", xsd),
  new XElement("sessionID", "some session id", new XAttribute("xmlns", api))
);

在没有 sessionID 的情况下,它愉快地使用 xsi 和 xsd 创建了主 headerResponse,但是当我添加 sessionID 并尝试 post 立即 window 中的内容时使用 example.toString(),我收到以下错误:

The prefix '' cannot be redefined from '' to 'http://www.example.com/portal-api' within the same start element tag.

您需要使用其完全限定名称(即包括其命名空间)来定义您的元素名称 sessionID。默认名称空间声明的插入将由 LINQ to XML:

自动处理
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XNamespace xsd = "http://www.w3.org/2001/XMLSchema";
XNamespace api = "http://www.example.com/portal-api";

XElement example = new XElement("headerResponse",
    new XAttribute(XNamespace.Xmlns + "xsi", xsi),
    new XAttribute(XNamespace.Xmlns + "xsd", xsd),
    new XElement(api + "sessionID", "some session id")
);   

您可以通过添加声明来控制声明,就像您已经完成的那样。例如,您可以为 api 添加一个带有根前缀的声明以简化结果:

XElement example = new XElement("headerResponse",
    new XAttribute(XNamespace.Xmlns + "xsi", xsi),
    new XAttribute(XNamespace.Xmlns + "xsd", xsd),
    new XAttribute(XNamespace.Xmlns + "api", api),
    new XElement(api + "sessionID", "some session id")
);   

请注意,虽然 XML 看起来与您要求的 XML 不同,但它们在语义上没有区别。