Solved

Create New XML Element

Posted on 2011-09-28
3
281 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
[X]
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
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

Monthly Recap

May was a big month for new releases from Linux Academy! Take a look at what our team built recently in our blog. You can access the newest releases from our blog.

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …

630 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