Xpath 小见

<?xml version="1.0" encoding="utf-8" ?>
<books>
  <book>
    <title>c#入门经典</title>
    <price>79.00</price>
    <author>ms</author>
  </book>
  <book>
    <title id="Best">c#高级编程</title>
    <price>128.00</price>
    <author>ms</author>
  </book>
  <book>
    <title type="构架">大话设计模式</title>
    <price>55.00</price>
    <author>中国</author>
  </book>
  <book>
    <title>MVC入门经典</title>
    <price>108.00</price>
    <author>美国</author>
  </book>
  <book>
    <title>SQL高级编程</title>
    <price>228.00</price>
    <author>ms</author>
  </book>
</books>

 

这是xml文件

说明:

"//" 表示特定名称下的所有节点,不一定是子节点。不会单独用,会这样用"//title" 选出 所有title节点

"/"  表示从根节点下开始查找,从根节点,上面的xml 就books的上一层,如"/books/book/title",选出从根节点出发而且匹配该模式的title节点

"title"  这里的title是一个节点的名称,看上面的xml,(选出的是该节点下的所有名称为title的子节点,是子节点),注意 //title  与 title 前者不需要子节点这个限定

属性选择 "title[@type='构架']",是不是像jquery的选择符号呢? 注意,加上@ 表示该节点的属性,而//book[price='228.00']

*表示全部,@表示属性,这两个前面不加任何修饰就表示 选择当前节点 @page 当前节点的一个page属性,* 表示当前节点的所有子节点, @*就表示所有属性,选择的是属性

title[2]  表示按照子节点的索引选出第二个title

text() 就表示文本啦

总结:.表示当前节点,..父节点, //所有模式匹配 , / 根节点(根元素的父元素),什么都没有就是与.的作用一样,当前元素

linq to xml

 public decimal GetRealPayRate(string typename)
        {
            string path = HttpContext.Current.Server.MapPath(AqiooInfo.AqiooAddCoinConfig);
            XDocument document = XMLService.Load(path);
            if (document != null)
            {
                 XElement node = document.Descendants("CoinTypes").Elements("CoinName").FirstOrDefault(p => p.Attribute("type").Value.Equals(typename));
                 if (node != null)
                 {
                     return Convert.ToDecimal(node.Attribute("payrate").Value.ToString());
                 }
            }
            return 1;
        }

posted on 2010-11-17 23:40  jianshaohui  阅读(190)  评论(1编辑  收藏  举报

导航