简体   繁体   中英

Adding element to existing XML node

Where am i going wrong???

I have an xml file with OppDetails as a tag already as shown below

<OppDetails>
  <OMID>245414</OMID> 
  <ClientName>Best Buy</ClientName> 
  <OppName>International Rate Card</OppName> 
  <CTALinkType>AO,IO,MC,TC</CTALinkType> 
  </OppDetails>
  </OppFact>

Now i am trying to add another element to it but getting an error in AppendChild method please help

XmlNode rootNode = xmlDoc.SelectSingleNode("OppDetails");
XmlElement xmlEle = xmlDoc.CreateElement("CTAStartDate");
xmlEle.InnerText = ExcelUtility.GetCTAStartDate();
rootNode.AppendChild(xmlEle);
            xmlDoc.Save("C:\\test.xml");
XmlElement xmlEle = xmlDoc.DocumentElement["OppDetails"];
XmlElement eleNew = xmlDoc.CreateElement("CTAStartDate");
eleNew.InnerText = ExcelUtility.GetCTAStartDate();
xmlEle.AppendChild(eleNew);
xmlDoc.Save("C:\\test.xml");

It is hard to tell without a full sample, but a common reason for SelectNodes / SelectSingleNode returning null is xml namespaces. If you xml makes use of element namespaces, you'll probably need to use an XmlNamespaceManager along with your query, and define a suitable alias for the namespace you want.

Is rootNode null ?

From MSDN on SelectSingleNode :

The first XmlNode that matches the XPath query or a null reference (Nothing in Visual Basic) if no matching node is found.

If rootNode is null , it indicates that the node could not be found, and trying to use the null rootNode would cause the exception you are seeing.

The exception you've reported means that you have not located the root element. When SelectSingleNode can't find the requested node, it returns null . You didn't check for that.

Read root node and add the new element in to the root node. I think you are trying to append in XML document.

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