按特定顺序编写 XML 属性和命名空间声明

nic*_*ald 4 c# xml xmlwriter xml-namespaces xml-attribute

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

<urn:Command complete="true" xmlns:urn="namespaceURI">
Run Code Online (Sandbox Code Playgroud)

所以我有一个元素Command ,一个命名空间,namespaceURI 一个前缀urn ,最后一个属性字符串,其中包含名称和completetrue ,但没有命名空间。

我为此编写的代码返回:

<urn:Command xmlns:urn="namespaceURI" complete="true">
Run Code Online (Sandbox Code Playgroud)

所以问题是我希望属性字符串位于 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;`
Run Code Online (Sandbox Code Playgroud)

kjh*_*hes 5

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

根据XML 建议,属性顺序并不重要

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

命名空间声明就像属性(W3C XML 推荐中的命名空间,第3 节声明命名空间),

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

具有类似的微不足道的排序。

因此,任何符合规范的 XML 工具或库都不会关心 XML 属性和 XML 命名空间声明的顺序,您也不应该关心。

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


...除了很少需要的标准化应用程序

XML 建议都认为属性排序和名称空间声明排序无关紧要,但如果您的应用程序不可避免地需要属性排序,请参阅XML 规范化建议规范 XML 建议有关属性处理的部分。需要为数字签名建立词法相等/不相等(XML 签名语法和处理版本 1.1)就是这样的例外之一。

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