Solved

Create New XML Element

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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This Micro Tutorial demonstrates using Microsoft Excel pivot tables, how to reverse engineer competitors' marketing strategies through backlinks.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

920 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now