How to create XmlElement attributes with prefix?

前端 未结 4 1378
不知归路
不知归路 2020-12-06 10:46

I need to be able to define an attribute with a prefix in a xml element.

For instance...




        
相关标签:
4条回答
  • 2020-12-06 11:37

    If you've already declared your namespace in the root node, you just need to change the SetAttribute call to use the unprefixed attribute name. So if your root node defines a namespace like this:

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

    You can do this and the attribute will pick up the prefix you've already established:

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

    If you have not yet declared the namespace (and its prefix), the three-string XmlDocument.CreateAttribute overload will do it for you:

    // 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);
    
    0 讨论(0)
  • 2020-12-06 11:40

    Try creating the attribute directly and adding it to the element:

    XmlAttribute attr = XmlDocToRef.CreateAttribute("s", "id", "http://niem.gov/niem/structures/2.0");
    attr.InnerText = "ID_Person_01";
    TempElement.Attributes.Append(attr);
    
    0 讨论(0)
  • 2020-12-06 11:47

    Since my search kept taking me here, I'll answer this for XElement. I don't know if this solution is also valid for XmlElement, but it will hopefully at least help others using XElement, who end up here.

    Based on this I added xml:space="preserve" to all data-nodes in some template, before looking up and adding their contents. It's weird code IMO (I would prefer three parameters as shown above, but it does the job:

     foreach (XElement lElement in root.Descendants(myTag))
     {
          lElement.Add(new XAttribute(root.GetNamespaceOfPrefix("xml") + "space", "preserve"));
     }
    
    0 讨论(0)
  • 2020-12-06 11:51

    The XMLDocument.CreateAttribute method can take 3 strings: specified Prefix, LocalName, and NamespaceURI. You could then add the attribute to the element. Something like this might work for you:

    XmlAttribute newAttribute = XmlDocToRef.CreateAttribute("s", "id", "http://niem.gov/niem/structures/2.0");
    TempElement.Attributes.Append(newAttribute):
    
    0 讨论(0)
提交回复
热议问题