Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Create New XML Element

Posted on 2011-09-28
3
278 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

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

828 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