2

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");
2
  • 2
    It would help to know what the error is. Commented Apr 19, 2010 at 3:39
  • Object reference not set to an instance of an object. Commented Apr 19, 2010 at 3:42

5 Answers 5

3
XmlElement xmlEle = xmlDoc.DocumentElement["OppDetails"];
XmlElement eleNew = xmlDoc.CreateElement("CTAStartDate");
eleNew.InnerText = ExcelUtility.GetCTAStartDate();
xmlEle.AppendChild(eleNew);
xmlDoc.Save("C:\\test.xml");
Sign up to request clarification or add additional context in comments.

2 Comments

Is this the solution to the problem?
It would be helpful to mark this as the accepted answer. Also, if you could provide any details as to why you were able to get this to work when your previous attempt failed it would help others.
2

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.

Comments

0

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.

Comments

0

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.

Comments

0

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

1 Comment

This should be a comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.