如何使用XElement,XAttribute添加XML命名空间值

时间:2015-02-13 16:47:16

标签: c# .net xml xelement xattribute

这是所需的(必需的)输出:

<BatchAttestationRequest xmlns="http://cms.gov/nlr/attestation/batch/request/1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://cms.gov/nlr/attestation/batch/request/1.0 BatchAttestationRequest.xsd ">

我找到了一些有用的帖子让我朝着正确的方向前进。 This question让我如此接近,但是在我这方面实施时,解决方案存在一些问题。

这是我的代码:

        XNamespace ns = @"http://cms.gov/nlr/attestation/batch/request/1.0";
        XNamespace xsi = @"http://www.w3.org/2001/XMLSchema-instance";


        XElement xml_file = new XElement(ns + "BatchAttestationRequest",
                                new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName),
                                new XAttribute(xsi + "schemaLocation", @"http://cms.gov/nlr/attestation/batch/request/1.0 BatchAttestationRequest.xsd "),
                                    header, // child nodes
                                    attestations,
                                    trailer);

我对此代码的问题:

  • 属性乱序; “xmlns”属性需要先出现
  • 我的根节点的每个子节点现在都有“xmlns =”“”作为属性。

我想完全上面的输出。

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要像为root用户一样设置元素的命名空间。例如新的XElement(ns +“Header”)