-1

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";
    
  
}
4
  • 1
    While XmlDocument will certainly work, I'd recommend using LINQ to XML instead - XDocument etc. It's a much more friendly API. I would recommend breaking the task into steps: 1) Load the document; 2) find the last element (or perhaps all elements?); 3) Convert the ID attribute into an integer (you can just cast to int with LINQ to XML); 4) Create a new element with the new ID; 5) add the new element to the document; 6) save the document. I'd recommend doing this in a console app, which is simpler than a GUI. Commented Dec 17, 2018 at 7:54
  • If you take each step at a time, you can ask a really specific question about the step that causes you the problem. You also need to consider what you want to happen if the ID isn't an integer, or is missing - looking at your existing XML document, that would happen quite a lot. Commented Dec 17, 2018 at 7:55
  • You already have missing and duplicate IDs.... And the last ID is not the highest. Be clear about your specifications. Commented Dec 17, 2018 at 8:00
  • Those random id's with yeppp etc was from when I testing it ill remove them Commented Dec 17, 2018 at 8:06

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);

2 Comments

I'm getting "Object reference not set to an instance of an object." error on var lastId = books.Descendants("book").Select(x => int.Parse(x.Attribute("ID").Value)).Last();
That is strange, i hope your xml is still the same as shown in OP ? and you have create instance of books as in the first line ? Also, attribute cases are still the same. ("ID" )
0
  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");

            }


        }

Comments

0
    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}");

1 Comment

Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.