【问题标题】:How to create XmlElement attributes with prefix?如何创建带前缀的 XmlElement 属性?
【发布时间】:2011-01-16 08:28:14
【问题描述】:

我需要能够在 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");

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

“:”字符,十六进制值 0x3A,不能包含在名称中。

如何定义带前缀的属性?

【问题讨论】:

    标签: c# xml


    【解决方案1】:

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

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

    【讨论】:

    • 这行得通。我已经在根节点中有命名空间。只需从 SetAttribute 方法的第一个参数中删除前缀。谢谢!
    • 非常有帮助。一件小事 - 缺少一个等于/赋值运算符 XmlAttribute attribute = xmlDocToRef.
    【解决方案2】:

    XMLDocument.CreateAttribute 方法可以采用 3 个字符串:指定的 Prefix、LocalName 和 NamespaceURI。然后,您可以将属性添加到元素。这样的事情可能对你有用:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        由于我的搜索一直把我带到这里,我会回答这个XElement。我不知道这个解决方案是否也适用于XmlElement,但希望它至少可以帮助使用XElement 的其他人,他们最终会在这里。

        基于this,我在某个模板中的所有数据节点中添加了xml:space="preserve",然后再查找并添加它们的内容。这是奇怪的代码 IMO(我更喜欢上面显示的三个参数,但它可以完成工作:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-21
          • 2014-12-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-15
          • 1970-01-01
          • 2014-08-06
          相关资源
          最近更新 更多