如何使用前缀创建XmlElement属性?

我需要能够在xml元素中定义带有前缀的属性。

例如…

 

为了做到这一点,我虽然以下会有效。

 XmlElement TempElement = XmlDocToRef.CreateElement("nc:Person", "http://niem.gov/niem/niem-core/2.0"); TempElement.SetAttribute("s:id", "http://niem.gov/niem/structures/2.0", "ID_Person_01"); 

不幸的是,当我收到下面的错误时,XmlElement.SetAttribute(string,string,string)似乎不支持解析前缀。

‘:’字符,hex值0x3A,不能包含在名称中。

如何定义带前缀的属性?

如果您已在根节点中声明了命名空间,则只需更改SetAttribute调用以使用未加前缀的属性名称。 因此,如果您的根节点定义了这样的命名空间:

  

您可以执行此操作,该属性将获取您已经建立的前缀:

 // no prefix on the first argument - it will be rendered as // s:id='ID_Person_01' TempElement.SetAttribute("id", "http://niem.gov/niem/structures/2.0", "ID_Person_01"); 

如果尚未声明命名空间(及其前缀),则三字符串XmlDocument.CreateAttribute重载将为您执行:

 // Adds the declaration to your root node var attribute = xmlDocToRef.CreateAttribute("s", "id", "http://niem.gov/niem/structures/2.0"); attribute.InnerText = "ID_Person_01" TempElement.SetAttributeNode(attribute); 

XMLDocument.CreateAttribute方法可以使用3个字符串:指定的前缀,LocalName和NamespaceURI。 然后,您可以将该属性添加到元素中。 这样的事可能适合你:

 XmlAttribute newAttribute = XmlDocToRef.CreateAttribute("s", "id", "http://niem.gov/niem/structures/2.0"); TempElement.Attributes.Append(newAttribute): 

尝试直接创建属性并将其添加到元素:

 XmlAttribute attr = XmlDocToRef.CreateAttribute("s", "id", "http://niem.gov/niem/structures/2.0"); attr.InnerText = "ID_Person_01"; TempElement.Attributes.Append(attr); 

由于我的搜索一直把我XElement这里,我会为XElement回答这个问题。 我不知道这个解决方案是否对XmlElement也有效,但希望它至少可以帮助其他人使用XElement ,而XElement最终会在这里结束。

基于此,我在查找并添加其内容之前,将xml:space="preserve"到某个模板中的所有数据节点。 这是奇怪的代码IMO(我更喜欢上面显示的三个参数,但它完成了这项工作:

  foreach (XElement lElement in root.Descendants(myTag)) { lElement.Add(new XAttribute(root.GetNamespaceOfPrefix("xml") + "space", "preserve")); }