【问题标题】:Writing XML attributes and namespace declarations in a specific order按特定顺序编写 XML 属性和命名空间声明
【发布时间】:2019-09-02 11:16:07
【问题描述】:

我正在尝试制作一个带有根元素的 XML 文件:

<urn:Command complete="true" xmlns:urn="namespaceURI">

所以我有一个元素Command 命名空间namespaceURI 前缀urn 最后是一个名称为complete 的属性字符串,其值为true,并且没有命名空间。

我为此编写的代码返回:

<urn:Command xmlns:urn="namespaceURI" complete="true">

所以问题是我希望属性字符串在 XML 文件中的命名空间定义之前,我在这个网站上找不到类似的问题。

我尝试编写一个带有前缀和命名空间的StartElement,然后编写一个没有命名空间的AttributeString,这将返回具有定义命名空间的根元素,然后是属性字符串。 我也尝试过只定义一个开始元素,然后定义两个属性字符串,但是我找不到将前缀写入开始元素的方法。

这是我的原始代码,它首先返回带有命名空间定义的根元素,然后是属性定义:

`Dim Writer as System.Xml.XmlWriter;
dim writerSettings  as System.Xml.XmlWriterSettings;
dim basePath as string;
dim source as string;
dim destination as string;

writerSettings = new System.Xml.XmlWriterSettings();
'writerSettings.ConformanceLevel= false;
'writerSettings.Encoding = new System.Text.UTF8Encoding(false);
writerSettings.OmitXmlDeclaration = false;

basePath = System.IO.Path.Combine("\\wnlcuieb502\WEI\Outbound","RolexSet");
source  = System.IO.Path.Combine(basePath,"\\wnlcuieb502\WEI\Outbound","TEST.XML");

Writer = System.Xml.XmlWriter.Create(source,writerSettings);
Writer.WriteStartDocument();

Writer.WriteStartElement("urn","SetPackagingOrder","urn:laetus.com:ws:tts:mes");
Writer.WriteAttributeString("complete",null,"true");
Writer.WriteEndElement();
Writer.WriteEndDocument();
Writer.dispose();


try
    destination = System.IO.Path.Combine(basePath,"TEST.XML");
    while not System.IO.File.Exists(destination)        
        System.IO.File.Move(source,destination);
    endwhile;
catch
    LogError(Me.HierarchicalName + ": Could not move XML file: "+ "TEST.XML" +" from " + source + " to " + destination + ", Error: " + error.Message);
endtry;`

【问题讨论】:

  • 您能否提供重现该问题的代码?使用您的代码,在命名空间声明(tried it)之前输出完整的属性,如果我理解正确,这就是您想要的。
  • @steve16351 我已经编辑了我的帖子以包含我使用的简化代码。该代码位于 Wonderware 名为 System platform 的程序上的脚本生成器中,因此开始时非常简化。使用此代码我仍然得到输出
  • 我还发现该程序使用 .Net 库,所以这可能就是我们存在差异的原因

标签: c# xml xml-namespaces xmlwriter xml-attribute


【解决方案1】:

XML 属性和命名空间声明顺序无关紧要

Attribute order is insignificantXML Recommendation:

请注意,开始标签中属性规范的顺序或 空元素标签不重要。

命名空间声明类似于属性(W3C Namespaces in XML Recommendation3 Declaring Namespaces 部分),

[定义:命名空间(或更准确地说,命名空间绑定)是 声明使用一系列保留属性。此类属性的名称必须是 xmlns 或以 xmlns: 开头。这些 属性,与任何其他 XML 属性一样,可以直接提供或 通过default。 ]

具有同样微不足道的排序。

因此,没有符合标准的 XML 工具或库会关心 XML 属性和 XML 命名空间声明的顺序,您也不应该关心。

这就是为什么 XML 库通常不提供约束属性排序的方法的原因,尝试这样做几乎总是表明您做错了。


...除了很少需要的规范化应用程序

XML 建议都将属性排序和命名空间声明排序视为无关紧要,但如果您的应用程序不可避免地需要属性排序,请参阅XML Normalization Recommendation 中的section on attribute processingCanonical XML Recommendation。为数字签名 (XML Signature Syntax and Processing Version 1.1) 建立词法等式/不等式的需求就是这样的一个例外。

另请参阅(但如果您绝对必须订购 XML 属性和命名空间声明):

【讨论】:

    猜你喜欢
    • 2019-05-06
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多