Ron Jeremy
Ron Jeremy

Reputation: 35

How to retrieve attribute from XML file in C#

I'm complete rookie I need to retrieve the value of last id in XML file here is my XML and then I want to add 1 to that to make a unique id. How would I go about doing that?

<?xml version="1.0" standalone="yes"?>
<bookstore>
      <book ID="yepppppppp" title="Harry Potter" price="10" quantity="100" />
      <book ID="1" title="Harry Potter" price="10" quantity="100" />
      <book ID="10" title="Harry Potter" price="10" quantity="100" />
      <book ID="10" title="Harry Potter" price="10" quantity="100" />
      <book title="Harry Potter" price="10" quantity="100" />
      <book title="Harry Potter" price="10" quantity="100" />
      <book title="Harry Potter" price="10" quantity="100" />
      <book title="Harry Potter" price="10" quantity="100" />
      <book ID="1" title="Dracula by Bam Stoker" price="14.95" quantity="11">
      </book>
      <book ID="2" title="The Virtues of War A Novel of Alexander the Great" price="10.95" quantity="5">
      </book>
      <book ID="3" title="Man Walks Into A Bar" price="9.00" quantity="6">
      </book>
      <book ID="4" title="Encyclopedia of Modern Bodybuilding" price="30.75" quantity="12">
      </book>
      <book ID="5" title="Your Mortgage and How to Pay it off in Five Years" price="15.00" quantity="4">
      </book>
</bookstore>

And C#

 protected void Button1_Click(object sender, EventArgs e)
{

    System.Xml.XmlDocument myXml = new System.Xml.XmlDocument();
    myXml.Load(Server.MapPath("~/purchases.xml"));
    System.Xml.XmlNode xmlNode = myXml.DocumentElement.FirstChild;
    System.Xml.XmlElement xmlElement = myXml.CreateElement("book");

    xmlElement.SetAttribute("ID", );
    xmlElement.SetAttribute("title", Server.HtmlEncode(txtTitle.Text));
    xmlElement.SetAttribute("price", Server.HtmlEncode(txtPrice.Text));
    xmlElement.SetAttribute("quantity", Server.HtmlEncode(txtQuantity.Text));

    myXml.DocumentElement.InsertBefore(xmlElement, xmlNode);
    myXml.Save(Server.MapPath("~/purchases.xml"));

    lblSumarry.Text = "Record inserted into XML file successfully";
    
  
}

Upvotes: -1

Views: 1111

Answers (4)

Sam
Sam

Reputation: 1

    XmlDocument doc2 = new XmlDocument();
    doc2.Load(@"C:\temp\BANK.XML");
    XmlNodeList branches = doc2.SelectNodes("BANK//Branches//Branch");
    foreach (XmlNode branch in branches)
    {
        XmlAttributeCollection branchAttribs = branch.Attributes;
        foreach (XmlAttribute attrib in branchAttribs)
        {
            Console.Write($"{attrib.Name}={attrib.Value}\t");                
        }
        Console.WriteLine();
    }
    Console.WriteLine($"Number of branches: {branches.Count}");

Upvotes: 0

Sandy Sing
Sandy Sing

Reputation: 11

  XmlDocument doc = new XmlDocument();
        doc.Load("Yourxmlfilepath.xml");

        //Display all the book titles.
        XmlNodeList xNodeList = doc.SelectNodes("/bookstore/book");
        foreach (XmlNode xNode in xNodeList)
        {

            var employeeName = xNode.OuterXml;
            XmlDocument docnew = new XmlDocument();
            docnew.LoadXml(employeeName);


            foreach (XmlElement report in docnew.SelectNodes("book"))
            {
                string ID = report.GetAttribute("ID");
                string title = report.GetAttribute("title");
                string quantity = report.GetAttribute("quantity");
                string price = report.GetAttribute("price");

            }


        }

Upvotes: 0

Anu Viswan
Anu Viswan

Reputation: 18155

As Jon suggested, you can use Linq To XML here.

XElement books = XElement.Load(filePath);
var lastId = books.Descendants("book").Select(x=>Int32.Parse(x.Attribute("ID").Value)).Last();

This will give you the last ID in the current list.You can now create your new Node

books.Add(new XElement("book",new XAttribute("ID",(lastId+1).ToString()),
                              new XAttribute("title","New Title"),
                              new XAttribute("price","1234")));
books.Save(filePath);

Upvotes: 0

Vishwa Ratna
Vishwa Ratna

Reputation: 6390

You can also use XPath within the Xml DOM like this :

string title;
XmlDocument xml = new XmlDocument();
xml.Load("~/purchases.xml"); 
// Or any other method to load your xml data in the XmlDocument.
// For example if your xml data are in a string, use the LoadXml method.
XmlElement elt = xml.SelectSingleNode("//SubMenu[@id='1']") as XmlElement;
if(elt!=null)
{
  name=elt.GetAttribute("title");  
}

Reference

Upvotes: 1

Related Questions