简体   繁体   中英

insert the new child node in existing xml based on id in C#

I want to add child node in existing xml

  <tblTemp> <Details> <LoginId>4</LoginId> <AId>2</AId> <OId>763</OId> <LDate>2016-09-26</LDate> <LTime>15:27:39</LTime> <ReasonId>1</ReasonId> <Flag>2</Flag> </Details> <Details> <LoginId>3</LoginId> <AId>2</AId> <OId>763</OId> <LDate>2016-09-26</LDate> <LTime>12:22:39</LTime> <ReasonId>4</ReasonId> <Flag>2</Flag> </Details> <Details> <LoginId>1</LoginId> <AId>1</AId> <OId>765</OId> <LDate>2016-09-26</LDate> <LTime>10:22:39</LTime> <ReasonId>4</ReasonId> <Flag>2</Flag> </Details> </tblTemp> 

And i want output like this

  <tblTemp> <Details> <LoginId>4</LoginId> <AId>2</AId> <OId>763</OId> <LDate>2016-09-26</LDate> <LTime>15:27:39</LTime> <FDate>2016-09-26</FDate> <FTime>16:50:30</FTime> <ReasonId>1</ReasonId> <Flag>2</Flag> </Details> <Details> <LoginId>3</LoginId> <AId>2</AId> <OId>763</OId> <LDate>2016-09-26</LDate> <LTime>12:22:39</LTime> <FDate>2016-09-26</FDate> <FTime>13:36:30</FTime> <ReasonId>4</ReasonId> <Flag>2</Flag> </Details> <Details> <LoginId>1</LoginId> <AId>1</AId> <OId>765</OId> <LDate>2016-09-26</LDate> <LTime>10:22:39</LTime> <FDate>2016-09-26</FDate> <FTime>11:53:45</FTime> <ReasonId>4</ReasonId> <Flag>2</Flag> </Details> </tblTemp> 

Based on LoginId I want to add child node in xml file.I have been trying code like this.

//code for adding child node
 string strDBDir = "C:\\XMLfile.xml";
                     try
                     {
                         DataSet dsxml = new DataSet();
                         DataView DvXML = null;
                         dsxml.ReadXml(strDBDir);
                         DvXML = dsxml.Tables[0].DefaultView;
                         DvXML.RowFilter = "AId = '" + AId + "'";

                         if (File.Exists(strDBDir))
                         {
                             if (DvXML.ToTable().Rows.Count > 0)
                             {
                                 LoginId = Convert.ToInt32(DvXML.ToTable().Rows[0]["LoginId"]);

                             XmlDocument originalXml = new XmlDocument();
                             originalXml.Load(strDBDir);
                             XmlNode TechReport = originalXml.SelectSingleNode("Details");
                             XmlNode Data = originalXml.CreateNode(XmlNodeType.Element, "FDate", null);
                             TechReport.AppendChild(Data);
                             originalXml.Save(strDBDir);
                         }
                     }
                     catch
                     {
                     }

For the above code i get an exception-"Object reference not set to an instance of an object" Can you please guide on this,how to add the FDate and Ftime in DBfile.xml based on LoginId and AId.I have been struggling for this.

You can achieve that by changing your search. Instead of the looking only for "Details" which will add the child elements randomly, use "Details[LoginId='4']"

XmlNode TechReport = originalXml.SelectSingleNode("Details[LoginId='4']");

Is this what you are looking for?

Also, I think you will need to use CreateElement instead of CreateNode

Using xml linq and changing all occurances

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication16
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            foreach (XElement detail in doc.Descendants("Details"))
            {
                detail.Add(new object[] {
                    new XElement("LTime", DateTime.Now.ToString("hh:mm:ss")),
                    new XElement("FDate", DateTime.Now.Date.ToShortDateString())
                });
            }

        }
    }
}

I think that

XmlNode TechReport = originalXml.SelectSingleNode("Details");

should be:

XmlNode TechReport = originalXml.SelectSingleNode("tblTemp/Details");

Or to be more precise:

XmlDocument originalXml = new XmlDocument();
originalXml.Load(strDBDir);
var TechReport = originalXml.SelectSingleNode($"tblTemp/Details[AId={AId}][LoginId={LoginId}]");
if (TechReport != null)
{
  XmlNode Data = originalXml.CreateNode(XmlNodeType.Element, "FDate", null);
  TechReport.AppendChild(Data);
  originalXml.Save(strDBDir);
}
else
{
  // Handle this as you see fit...
}

you can try this way to adding a new child:

 XmlDocument xml = new XmlDocument();
 xml.Load(strDBDir);
 XmlNodeList xnList = xml.SelectNodes("/tblTemp/Details");
 foreach (XmlNode xn in xnList)
 {
    // here your **if** statement with check on loginId in **xn**
    XElement child = new XElement("FDate"); 
    child.SetValue("2016-09-26");
    xn.AppendChild(child);
 }

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