需要帮助将命名空间代码从 XmlWriter 转换为 XmlDocument

Need help to convert namespace code from XmlWriter to XmlDocument

两个小时后,我尝试用 XmlWriter 将 4 行旧代码翻译成 XmlDocument,但我失败了! ;(

XmlWriter.WriteStartDocument();
XmlWriter.WriteStartElement("document", "urn:hl7-org:v3");
XmlWriter.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
XmlWriter.WriteAttributeString("schemaLocation", "http://www.w3.org/2001/XMLSchema-instance", "urn:hl7-org:v3 GUDIDSPL.xsd");

我的台词:

 XmlDeclaration xmlDeclaration = XmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null);
 XmlElement root = XmlDocument.CreateElement(string.Empty, "document", "urn:hl7-org:v3");
 XmlDocument.AppendChild(root);
 XmlDocument.InsertBefore(xmlDeclaration, root);

这是唯一可行的方法,此后我尝试的所有代码都失败了。 我没有得到 100% 正确的命名空间! 原因之一是 "SetAttribute",不提供前缀参数。

希望能帮到你

亲切的问候

跟进问题:

我实现了 "har07" 的代码 postet,效果很好! 但我现在有不同的问题。

输出应如下所示:

< document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:hl7-org:v3 GUDIDSPL.xsd" xmlns="urn:hl7-org:v3">
<id root="1fed661f-e015-4ea9-95e5-7cf293cd0517" />
<code code="C101716" codeSystem="2.16.840.1.113883.3.26.1.1" />
<effectiveTime xsi:type="TS" value="20160212" />

但它看起来像这样:

< document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:hl7-org:v3 GUDIDSPL.xsd" xmlns="urn:hl7-org:v3">
<id root="6c4bb64e-d652-4fe6-80f1-8599196719d0" xmlns="" />
<code code="C101716" codeSystem="2.16.840.1.113883.3.26.1.1" xmlns="" />
<effectiveTime xsi:type="TS" value="20160212" xmlns="" />

我的创建元素代码总是生成这个空的 xmlns 标签。 我添加到我的 namespaceManager ("xsi", "http://www.w3.org/2001/XMLSchema-instance")

使用SetAttribute(),可以直接指定前缀和属性本地名作为第一个参数:

....
XmlElement root = XmlDocument.CreateElement(string.Empty, "document", "urn:hl7-org:v3");
root.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
root.SetAttribute("xsi:schemaLocation", "urn:hl7-org:v3 GUDIDSPL.xsd");
....

另一种选择是使用更新的 API、XDocument,而不是 XmlDocument

XNamespace d = "urn:hl7-org:v3";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
var doc = 
    new XDocument(
        new XDeclaration("1.0", "UTF-8", null),
        new XElement(d + "document",  //create root element in default namespace
            new XAttribute("xmlns", d.ToString()), //add default namespace declaration
            new XAttribute(XNamespace.Xmlns + "xsi", xsi.ToString()), //add xsi namespace declaration
            new XAttribute(xsi + "schemaLocation", "urn:hl7-org:v3 GUDIDSPL.xsd") //add xsi:schemaLocation attribute
        )
    );

更新:

应该使用 SetAttribute() 接受命名空间 uri 的重载来定义命名空间中的属性,即 xsi:schemaLocation :

....
XmlElement root = XmlDocument.CreateElement(string.Empty, "document", "urn:hl7-org:v3");
root.SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
root.SetAttribute("schemaLocation", "http://www.w3.org/2001/XMLSchema-instance", "urn:hl7-org:v3 GUDIDSPL.xsd");
....