karpagam
karpagam

Reputation: 21

Want to save particular node into the Xml File using c#

  1. code below:

    protected void generate_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        doc.PreserveWhitespace = true;
        doc.Load("XmlFileName");
        XmlNode node = doc.SelectSingleNode("ChartData/XaxisFields/XaxisField");
        if (node != null)
        {
            node.ChildNodes.Item(0).InnerXml = "hi";
            doc.Save("XmlFileName");
        }
    
     }   
    
  2. Showing null refernce here,

    node.ChildNodes.Item(0).InnerXml = "hi";
    
  3. Is the code is correct,the code behind running not showing any error but the Xaxisfield is not added.

    <?xml version="1.0" encoding="utf-8" ?>
    <ChartData>
      <XaxisFields>
        <XaxisField></XaxisField>
      </XaxisFields>
    </ChartData>
    
  4. List item

I want to add the childnode Xaxisfield in the xml file by selcting the particular parent node

Upvotes: 0

Views: 1445

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236288

You can use Linq to Xml to select your node and update its value:

var xdoc = XDocument.Load("XmlFileName");
xdoc.Root.Element("XaxisFields").Element("XaxisField").Value = "hi";
// OR
// xdoc.XPathSelectElement("//XaxisField").Value = "hi";
xdoc.Save("XmlFileName");

Also your code is not working because there is no child nodes of XaxisField node. This will work:

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load("XmlFileName");
XmlNode node = doc.SelectSingleNode("ChartData/XaxisFields/XaxisField");
if (node != null)
{
    node.InnerXml = "hi";
    doc.Save("XmlFileName");
}

Upvotes: 2

Related Questions