简体   繁体   中英

How to retrieve attribute from XML file in C#

我是新手,我需要检索XML文件中最后一个id的值,这里是

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

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

            }


        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM