Solved

Create New XML Element

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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

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…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

746 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

13 Experts available now in Live!

Get 1:1 Help Now