代码之家  ›  专栏  ›  技术社区  ›  Eddie

如何用前缀创建xmlElement属性?

  •  6
  • Eddie  · 技术社区  · 16 年前

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

    例如。。。

    <nc:Person s:id="ID_Person_01"></nc:Person>
    

    为了做到这一点,我认为以下几点是可行的。

    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");
    

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

    名称中不能包含十六进制值0x3a的“:”字符。

    如何定义带前缀的属性?

    4 回复  |  直到 13 年前
        1
  •  18
  •   Jeff Sternal    15 年前

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

    <People xmlns:s='http://niem.gov/niem/structures/2.0'>
    

    您可以这样做,属性将获取已经建立的前缀:

    // 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);
    
        2
  •  2
  •   Peter Jacoby    16 年前

    这个 XMLDocument.CreateAttribute 方法可以采用3个字符串:指定的前缀、localname和namespaceuri。然后可以将属性添加到元素中。这样的事情可能对你有用:

    XmlAttribute newAttribute = XmlDocToRef.CreateAttribute("s", "id", "http://niem.gov/niem/structures/2.0");
    TempElement.Attributes.Append(newAttribute):
    
        3
  •  1
  •   Jeff Hornby    16 年前

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

    XmlAttribute attr = XmlDocToRef.CreateAttribute("s", "id", "http://niem.gov/niem/structures/2.0");
    attr.InnerText = "ID_Person_01";
    TempElement.Attributes.Append(attr);
    
        4
  •  0
  •   Yahoo Serious    15 年前

    因为我的搜索一直把我带到这里,我会回答这个 XElement . 我不知道这个解决方案是否也适用于 XmlElement 但它至少能帮助其他人使用 X元素 最后来到这里。

    基于 this 我补充说 xml:space="preserve" 在查找和添加其内容之前,发送到某些模板中的所有数据节点。这是一个奇怪的代码imo(我更喜欢上面所示的三个参数,但它可以做到:

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