Reputation: 803
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");
Upvotes: 2
Views: 12007
Reputation: 179
Read root node and add the new element in to the root node. I think you are trying to append in XML document.
Upvotes: 0
Reputation: 1062780
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.
Upvotes: 2
Reputation: 803
XmlElement xmlEle = xmlDoc.DocumentElement["OppDetails"];
XmlElement eleNew = xmlDoc.CreateElement("CTAStartDate");
eleNew.InnerText = ExcelUtility.GetCTAStartDate();
xmlEle.AppendChild(eleNew);
xmlDoc.Save("C:\\test.xml");
Upvotes: 3
Reputation: 161773
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.
Upvotes: 0
Reputation: 24232
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.
Upvotes: 0