简体   繁体   中英

XML adding child element to existing XML element

I have the following XML element:

<ctext:RootAugmentation>

</ctext:RootAugmentation>

I would like to add the following element inside the above element:

<ctext:DetailsText>Example</ctext:DetailsText>

I have the following code:

string filename = @"C:\test.xml";
XmlDocument doc = new XmlDocument();
doc.LoadXml(File.ReadAllText(filename));
XmlNodeList elemList = doc.GetElementsByTagName("ctext:RootAugmentation");
XmlElement detailsElement = doc.CreateElement("ctext:DetailsText");
detailsElement.InnerText = "Example";
if (elemList.Count == 1)
{
    for (int i = 0; i < elemList.Count; i++)
    {
        Console.WriteLine(elemList[i].InnerText);
        elemList[i].AppendChild(detailsElement);
    }

    doc.Save(filename);
}
else 
{
    // update existing "ctext:DetailsText" value
}

I'm able to add the child element but tags are wrong:

<ctext:RootAugmentation>
         <DetailsText>Example narrative</DetailsText>
</ctext:RootAugmentation>

I'd like it to go in as:

 <ctext:DetailsText>Example narrative</ctext:DetailsText>

The prefix is just a way to not have to specify the namespace in every element that uses it, the namespace is most probably specified in the document the first time the prefix is used

To find the namespace URI, you can either look in the XML document and find the attribute that looks like:

<ctext:SomeElement xmlns:ctext="<namespace uri>">...

Once you have found it, you can use the CreateElement(string, string) overload to specify the namespaceUri.

doc.CreateElement("DetailsText", "<namespace uri for ctext>");

This will result in the element looking like:

<ctext:DetailsText />

You can specify the prefix in the CreateElement call ie "ctext:DetailsText" (Or by another overload), but this will automatically be looked up based on the namespaceUri you provide so in your case it's unnecessary. If you were to specify a different prefix, this will register the new prefix with the namespaceUri and add a new xmlns attribute on the element (which you don't want).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM