Solved

Create New XML Element

Posted on 2011-09-28
3
277 Views
Last Modified: 2013-12-17
I have a function I just finished that updates nodes values. What I'm trying to find out is if there is an easy way to add a new Element (Meter) if it does not already exist.

<Meter>
      <ID>3</ID>
      <Title>TEST4</Title>
</Meter>

public static bool UpdateConfig(string xPathExpr,string NodeName,string NewValue)
{
    // xPathExpr = /Document/MeterTree/Meter[Title='Test1']
    if (Path_FileConfiguration == null || xPathExpr == null || NodeName == null) { return false; }
    if (System.IO.File.Exists(Path_FileConfiguration) == false) { return false; }

    XmlElement NewElement;
    XmlDocument doc = new XmlDocument();
    doc.Load(Path_FileConfiguration);
    XmlNode node = doc.SelectSingleNode(xPathExpr);            

    if (!(node == null))
    {
        if (node.SelectSingleNode(NodeName) == null)
        {   //If Title is found but NodeName does not exist create it.
            NewElement = doc.CreateElement(NodeName);
            NewElement.InnerText = NewValue;
            node.AppendChild(NewElement);
        }
        else
        {   // Update NodeName
            XmlElement nameEle = (XmlElement)(node.SelectSingleNode(NodeName));
            nameEle.InnerText = NewValue;
        }
    } 
    else
    {   // Need to create the Element
                
    }
    doc.Save(Path_FileConfiguration);
    return true;
}

Open in new window

<?xml version="1.0"?>
<Document>
  <Configuration>
    <VersionInfo AppVersion="1.0.0.0" FileUpdated="9/28/2011 11:35:57 AM" />
  </Configuration>
  <MeterTree>
    <Meter>
      <ID>0</ID>
      <Title>Test1</Title>
    </Meter>
    <Meter>
      <ID>1</ID>
      <Title>Test2</Title>
    </Meter>
    <Meter>
      <ID>2</ID>
      <Title>Test3</Title>
    </Meter>
  </MeterTree>
</Document>

Open in new window

0
Comment
Question by:thaburner
3 Comments
 
LVL 4

Expert Comment

by:theHollow
ID: 36720349
Hello
I would, if possible, to this in different steps.
I would create a new class "MyMeterClass", which holds two properties : "ID" and "Title".
Then I would create a list of that class, and read from the XML file to that list on ex. program start.

List<MyMeterClass> meterlist = null;
XmlElement elt = null;
XmlDocument doc = null;

meterlist  = new List<MyMeterClass>();
doc = new XmlDocument();
doc.Load(Path_FileConfiguration);
elt = doc.DocumentElement["Document"]["MeterTree"];

foreach (XmlNode node in elt.ChildNodes)
{
    // read all Meters into the MyMeterClass list
    MyMeterClass meterclass = new MyMeterClass();
    meterclass.ID = node["ID"].InnerText;
    meterclass.Title= node["Title"].InnerText;

    meterlist.Add(meterclass);
}

Open in new window


Then, I would code only with the list. Check if an item exist in the list, add and remove from the list.
And when I close the app, or press a button (or whenever), I would write the list back to the XML file and save it.

That would be a simpler approach for me.

Hope it helps :-)
0
 
LVL 11

Accepted Solution

by:
Sudhakar Pulivarthi earned 500 total points
ID: 36811294
Hi,

In the else part u can create the xml nodes with this code:

// Need to create the Element
XmlElement element = doc.CreateElement("Meter");

XmlElement idChild = doc.CreateElement("ID");
idChild.InnerText = "3";
XmlElement titleChild = doc.CreateElement("Title");
titleChild.InnerText = "Test4";

element.AppendChild(idChild);
element.AppendChild(titleChild);

node.AppendChild(element);
0
 

Author Closing Comment

by:thaburner
ID: 36892009
I was able to get this solution to work perfect, thanks.
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question