phoenix13

导航

 

https://msdn.microsoft.com/en-us/library/bb943906.aspx

Basic Queries (LINQ to XML)

1. add to xml document

 public void sendMsg(string senderID, string receiverID, string msg)
        {
            String path = HostingEnvironment.MapPath(@"/App_Data/msgdb.xml");
            XElement root = XElement.Load(path);
            root.Add(
                new XElement("msg",
                    new XElement("sendid", senderID),
                    new XElement("rcvid", receiverID),
                    new XElement("content", msg)
            ));
            root.Save(path);
        }

2. query xml using linq

 public string[] receiveMsg(string receiverID)
        {
            String path = HostingEnvironment.MapPath(@"/App_Data/msgdb.xml");
            XElement root = XElement.Load(path);
            IEnumerable<String> query =
                from i in root.Elements("msg")
                where ((string)i.Element("rcvid")).Trim() == receiverID
                select (string)i.Element("content");
            string[] result = new string[query.Count()];
            for (int i = 0; i < query.Count(); i++)
            {
                result[i] = query.ElementAt(i);
            }
            return result;
        }

xml used in example

<?xml version="1.0" encoding="utf-8"?>
<msgs>
  <msg>
    <sendid>
      123
    </sendid>
    <rcvid>
      321
    </rcvid>
    <content>
      hello
    </content>
  </msg>
  <msg>
    <sendid>555</sendid>
    <rcvid>666</rcvid>
    <content>lily i love you</content>
  </msg>
</msgs>

 

posted on 2015-04-13 15:22  phoenix13  阅读(192)  评论(0编辑  收藏  举报