【问题标题】:XmlDocument CreateElement without xmlns under a prefixed elementXmlDocument CreateElement 在前缀元素下没有 xmlns
【发布时间】:2013-10-24 17:00:54
【问题描述】:

我正在尝试使用以下代码中的 C# XmlDocument 类向 ebay FindingAPI Web 服务编写 SOAP 请求:

XmlDocument doc = new XmlDocument();
XmlElement root = (XmlElement)doc.AppendChild(doc.CreateElement("soap", "Envelope", "http://www.w3.org/2003/05/soap-envelope"));
root.SetAttribute("xmlns", "http://www.ebay.com/marketplace/search/v1/services");
XmlElement header = (XmlElement)root.AppendChild(doc.CreateElement("soap", "Header", "http://www.w3.org/2003/05/soap-envelope"));
XmlElement body = (XmlElement)root.AppendChild(doc.CreateElement("soap", "Body", "http://www.w3.org/2003/05/soap-envelope"));
XmlElement request = (XmlElement)body.AppendChild(doc.CreateElement("findItemsByKeywordsRequest"));
XmlElement param = (XmlElement)request.AppendChild(doc.CreateElement("keywords"));
param.InnerText = "harry potter phoenix";

并且,上述代码的 XML 输出为:

<soap:Envelope xmlns="http://www.ebay.com/marketplace/search/v1/services" xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
    <soap:Header />
    <soap:Body>
        <findItemsByKeywordsRequest xmlns="">
            <keywords>harry potter phoenix</keywords>
        </findItemsByKeywordsRequest>
    </soap:Body>
</soap:Envelope>

但是,由于 findItemsByKeywordsRequest 元素中的额外 xmlns="" 属性,服务器无法识别此 XML。所需的 XML 输出应如下所示:

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns="http://www.ebay.com/marketplace/search/v1/services">
    <soap:Header/>
    <soap:Body>
        <findItemsByKeywordsRequest>
            <keywords>harry potter phoenix</keywords>
        </findItemsByKeywordsRequest>
    </soap:Body>
</soap:Envelope>

有谁知道我的代码有什么问题,请给我一些提示。谢谢!

【问题讨论】:

    标签: c# xml xml-namespaces xmldocument prefix


    【解决方案1】:

    因为您的文档在最外层元素中声明了默认命名空间,所以您必须在每个子元素上重复该命名空间以避免添加额外的空元素。

    更改 requestparam 元素声明以包含 "http://www.ebay.com/marketplace/search/v1/services" 命名空间

    XmlElement request = (XmlElement)body.AppendChild(doc.CreateElement("findItemsByKeywordsRequest", "http://www.ebay.com/marketplace/search/v1/services"));
    XmlElement param = (XmlElement)request.AppendChild(doc.CreateElement("keywords", "http://www.ebay.com/marketplace/search/v1/services"));
    

    通过这些更改,您的代码将生成以下 XML:

    <soap:Envelope xmlns="http://www.ebay.com/marketplace/search/v1/services" xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
        <soap:Header />
        <soap:Body>
            <findItemsByKeywordsRequest>
                <keywords>harry potter phoenix</keywords>
            </findItemsByKeywordsRequest>
        </soap:Body>
    </soap:Envelope>
    

    【讨论】:

    • 哦!我得到了它。非常感谢你! :D
    猜你喜欢
    • 2015-06-15
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 2012-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多