Adding an element to an existing XML node

Where am I wrong ???

I have xml file with OppDetails as 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 item to it, but getting 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");

      

+2


a source to share


5 answers


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

      



+3


a source


Hard to tell without a complete example, but a common reason for returning SelectNodes

/ SelectSingleNode

null

is the xml namespace. If the xml uses element namespaces, you will probably need to use XmlNamespaceManager

along with your query and define an appropriate alias for the required namespace.



+2


a source


Is it rootNode

null

?

From MSDN to SelectSingleNode

:

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

If rootNode

- null

, it means the node cannot be found and trying to use null rootNode

will result in what you see.

0


a source


The exception you reported means you did not find the root element. If SelectSingleNode

it cannot find the requested node, it returns null

. You haven't tested this.

0


a source


Read the root node and add a new item to the root node. I think you are trying to add to XML document.

0


a source







All Articles