C#, XML, adding new nodes

前端 未结 2 838
清酒与你
清酒与你 2020-11-30 12:12

I am trying to add new nodes to an existing XML file. i have this file with first test elements in it:

 
<         


        
相关标签:
2条回答
  • 2020-11-30 12:26

    I have the same trouble, with root==null, but MSDN helped me.

    You need to use // instead of /

    XmlNode root = xmldoc.SelectSingleNode("//ns:Root//ns:profesori", nsMgr);
    
    0 讨论(0)
  • 2020-11-30 12:28

    Your first problem is that the node names in your XPath don't match those of the XML. XML is case sensitive, so you need to use Root, not root:

    XmlNode root = xmldoc.SelectSingleNode("/ns:Root/ns:profesori", nsMgr);
    

    Next, instead of xmldoc.NamespaceURI, use the actual namespace uri:

    string strNamespace= "http://prpa.org/XMLSchema1.xsd";
    nsMgr.AddNamespace("ns", strNamespace);
    

    or do this:

    string strNamespace= xmldoc.DocumentElement.NamespaceURI;
    nsMgr.AddNamespace("ns", strNamespace);
    

    The NamespaceURI of an XmlDocument object will always be an empty string.

    And you should also use this namespace when creating your elements:

    XmlNode prof = xmldoc.CreateNode(XmlNodeType.Element, "profesor", strNamespace);
    
    XmlNode ime = xmldoc.CreateNode(XmlNodeType.Element, "ime", strNamespace);
    ime.InnerText = name;
    prof.AppendChild(ime);
    
    XmlNode prezime = xmldoc.CreateNode(XmlNodeType.Element, "prezime", strNamespace);
    prezime.InnerText = surname;
    prof.AppendChild(prezime);
    
    root.AppendChild(prof);
    

    You might also consider using the CreateElement() method, which would be slightly shorter:

    XmlNode prof = xmldoc.CreateElement("profesor", strNamespace);
    

    Or, my preference would be to use an XmlWriter:

    using(XmlWriter writer = root.CreateNavigator().AppendChild())
    {
        writer.WriteStartElement("profesor", strNamespace);
        writer.WriteElementString("ime", strNamespace, name);
        writer.WriteElementString("prezime", strNamespace, surname);
        writer.WriteEndElement();
    }
    
    0 讨论(0)
提交回复
热议问题