将 xsi:type 添加到我的 XML 文档中



>我有一个代码来使用此 Web 服务方法提取 XML 文档类型

XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XAttribute attribute = new XAttribute(xsi + "type", "xsd:string");
XElement node_user_id = new XElement("user_id", attribute, user.code);
XDocument doc = new XDocument(new XElement("ranzcp_user", new XAttribute(XNamespace.Xmlns + "ns1", "urn:logon"), node_user_id));
 XmlDocument xmldoc = new XmlDocument();
 xmldoc.LoadXml(elem.ToString());

使用上面的代码,我能够像这样提取一个xml文档:

<ranzcp_user xmlns:ns1="urn:logon">
   <user_id xmlns:p3="http://www.w3.org/2001/XMLSchema-instance" p3:type="xsd:string">12345678</user_id>
</ranzcp_user>

但我真正需要的是这个:

<ranzcp_user xmlns:ns1="urn:logon">
    <user_id  xsi:type="xsd:string">12345678</user_id>
</ranzcp_user>  

有什么方法可以获取 xml 所需的格式,其次,在解析 xml 数据时是否需要 xsi:type="xsd:string" 属性?

啪!

您可以显式定义命名空间前缀,以便使用规范xsi而不是p3

var doc = new XDocument(
    new XElement("ranzcp_user",
        new XAttribute(XNamespace.Xmlns + "ns1", "urn:logon"),
        new XAttribute(XNamespace.Xmlns + "xsi", xsi),
        new XElement("user_id", 12345678,
            new XAttribute(xsi + "type", "xsd:string")
            )
        )
    );

看到这个小提琴。这为您提供:

<ranzcp_user xmlns:ns1="urn:logon" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <user_id xsi:type="xsd:string">12345678</user_id>
</ranzcp_user>

但是,如前所述,完全删除命名空间前缀将导致无效的 XML - 没有符合要求的处理器允许您创建或读取它而不会出错。

可能是"必需的"XML 在其中一个父元素中声明了此前缀吗? 如果没有,我建议这是一个错误,您应该在花时间尝试删除该属性之前对此进行调查。我怀疑当使用者发现XML无效时,您最终会撤消所有这些工作。

最新更新