如何添加多个命名空间声明一个XDocument? [英] How do I add multiple Namespace declarations to an XDocument?

查看:1149
本文介绍了如何添加多个命名空间声明一个XDocument?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个XDocument建立一个已知结构的XML文档。我想建立的结构如下:

I'm using an XDocument to build an Xml document in a known structure. The structure I am trying to build is as follows:

<request xmlns:ns4="http://www.example.com/a" xmlns:ns3="http://www.example.com/b" xmlns:ns2="http://www.example.com/c" >
    <requestId>d78d4056-a831-4c7d-a357-d14402f623fc</requestId>
    ....
</request>



请注意的xmlns:NSX属性

Notice the "xmlns:nsX" attributes.

我想,没有成功,这些属性添加到我的请求元素。

I am trying, without success, to add these attributes to my "request" element.

XNamespace ns4 = XNamespace.Get("http://www.example.com/a");
XNamespace ns3 = XNamespace.Get("http://www.example.com/b");
XNamespace ns2 = XNamespace.Get("http://www.example.com/c");

XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "no"),
    new XElement("request",
        new XAttribute("ns4", ns4),
        new XAttribute("ns3", ns3),
        new XAttribute("ns2", ns2),
        new XElement("requestId", Guid.NewGuid())
     )
);



不过,这会产生以下内容:

However, this produces the following:

<request ns4="http://www.example.com/a" ns3="http://www.example.com/b" ns2="http://www.example.com/c">
  <requestId>38b07cfb-5e41-4d9a-97c8-4740c0432f11</requestId>
</request>



我如何正确添加命名空间声明?

How do I add the namespace declarations correctly?

推荐答案

你的意思是:

            new XAttribute(XNamespace.Xmlns + "ns4", ns4),
            new XAttribute(XNamespace.Xmlns + "ns3", ns3),
            new XAttribute(XNamespace.Xmlns + "ns2", ns2),

这篇关于如何添加多个命名空间声明一个XDocument?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆