如何从C#中的XML文件检索属性

时间:2018-12-17 07:51:18

标签: c# asp.net xml

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

3 个答案:

答案 0 :(得分:1)

您还可以像这样在Xml DOM中使用XPath:

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

答案 1 :(得分:0)

如乔恩建议的那样,您可以在此处使用Linq To XML。

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

这将为您提供当前列表中的最后一个ID。您现在可以创建新的节点

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

答案 2 :(得分: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");

            }


        }