首页 > 解决方案 > 无法创建 XElement 值包含“:”的 XML

问题描述

我有以下代码:

    private string GetXmlBody()
    {
        XNamespace ns = "http://schemas.xmlsoap.org/soap/envelope/";
        XNamespace xsdNs = "http://www.w3.org/2001/XMLSchema";
        XNamespace xsiNs = "http://www.w3.org/2001/XMLSchema-instance";
        XNamespace outNs = "http://soap.sforce.com/2005/09/outbound";
        XNamespace sfNs = "urn:sobject.enterprise.soap.sforce.com";

        XDocument requestXml = new XDocument(
            new XElement(ns + "Envelope", new XAttribute(XNamespace.Xmlns + "soapenv", ns), new XAttribute(XNamespace.Xmlns + "xsd", xsdNs), new XAttribute(XNamespace.Xmlns + "xsi", xsiNs),
                new XElement(ns + "Body",
                    new XElement(outNs + "notifications", new XAttribute("xmlns", outNs),
                        new XElement(outNs + "OrganizationId", runInfo.OrgId),
                        new XElement(outNs + "SessionId", runInfo.SessionId),
                        new XElement(outNs + "EnterpriseUrl", runInfo.Location),
                        new XElement(outNs + "Notification",
                            new XElement(outNs + "Id", "04l0H000014TY73QAG"),
                            new XElement(outNs + "sObject", new XAttribute(XNamespace.Xmlns + "sf", sfNs), new XAttribute(xsiNs + "type", "sf:" + runInfo.RecordType),
                                new XElement(sfNs + "Id", runInfo.RecordId),
                                new XElement(sfNs + runInfo.Field, runInfo.FieldValue)
                            )
                        )
                    )
                )
            )
        );

        return requestXml.ToString();
    }

这将生成所需的 XML,但是我遇到了以下错误:

System.Xml.XmlException : The ':' character, hexadecimal value 0x3A, cannot be included in a name.

由于runInfo.FieldValue包含的值:。例如,该值可能如下所示:

Opportunity:006i000000sidsh;Account:;userId:a016S00000sjsiq;sandbox:true

到目前为止,我看到的所有解决方案或类似问题都围绕着产生正确的元素名称,我的问题是围绕着价值。例如,如果我:runInfo.FieldValue变量中删除 ,则生成预期的 XML。

关于如何解决这个问题的任何想法?我已经尝试过对字符串进行 URL 编码,但这只会导致类似的错误,只是它抱怨%值。

标签: c#xmlxelement

解决方案


推荐阅读