Adding elements to an xml file in C#

前端 未结 7 1065
名媛妹妹
名媛妹妹 2020-11-27 19:00

I have an XML file formatted like this:


  
    
      testcode1
    
  &l         


        
相关标签:
7条回答
  • 2020-11-27 19:38

    This is extension to answers above, if your xml has namespace defined (xmlns) then you will get a nasty side effect when adding children - xmlns = "" being added to your new child element.

    What you want to do (assuming element you are adding belongs to same namespace as his parent) is to take namespace from parent element parentElement.GetDefaultNamespace().

    var child = new XElement(parentElement.GetDefaultNamespace()+"Snippet", new XAttribute("Attr1", "42"), new XAttribute("Attr2", "22"));
    child.Add(new XAttribute("Attr3", "777"));
    parentElement.Add(child);
    

    for parent elements with multiple namespaces you can choose which one to use by changing from parentElement.GetDefaultNamespace()+"Snippet" to parentElement.GetNamespaceOfPrefix("namespacePrefixThatGoesWithColon")+"Snippet" e.g

    var child = new XElement(parentElement.GetNamespaceOfPrefix("namespacePrefixThatGoesWithColon")+"Snippet", new XAttribute("Attr1", "42"), new XAttribute("Attr2", "22"));
    
    0 讨论(0)
提交回复
热议问题