如何读取XML特定的标签? [英] How to read specific tag in XML?

查看:410
本文介绍了如何读取XML特定的标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的xml文件

<?xml version="1.0" encoding="utf-8" ?>
  <Colleges>
    <College id="1" >
        <Name>Guru Kashi University</Name>
        <ShortName>GKU</ShortName>
        <Address>Talvandi Sabo</Address>
        <City>Bathinda</City>
        <Contact>09876543210</Contact>    
     </College>

     <College id="2" >
        <Name>Shaheed Udham Singh</Name>
        <ShortName>SUS</ShortName>
        <Address>Tangori</Address>
        <City>Mohali</City>
        <Contact>01234567890</Contact>    
     </College>
  </Colleges>

我想读的所有属性学院标签其中id = 1

I want to read all the attributes College tag where id =1

但我不知道如何读

推荐答案

您可以做到这一点使用LINQ非常方便的XML。假设你有一个字符串,上面的XML:

You can do this with LINQ to XML very easily. Assuming you have the XML above a string:

// Use XDocument.Load(fileName) if the XML is in file.
XDocument xDoc = XDocument.Parse(xml); // xml is the XML string

var query = from x in xDoc.Descendants("College")
            where x.Attribute("id").Value == "1"
            select x.Elements;

上面会给你所有的有1一个id的学院元素下的元素的集合。

The above will give you a collection of all the elements under the College element that has an id of 1.

另外,你可以创建一个匿名类型:

Alternatively, you can create an anonymous type:

var query = (from x in xDoc.Descendants("College")
             where x.Attribute("id").Value == "1"
             select new {
                 Name = x.Element("Name").Value,
                 ShortName = x.Element("ShortName").Value,
                 Address = x.Element("Address").Value,
                 City = x.Element("City").Value,
                 Contact = x.Element("Contact").Value
             }).SingleOrDefault();

在这种情况下,我用的SingleOrDefault来获取唯一的价值(或没有价值,如果没有找到的话);如果你可以有一个以上的ID= 1,则删除SingelOrDefault,你就会有匿名类型的集合。

In this case, I used SingleOrDefault to get the only value (or no value if it isn't found); if you could have more than one "id"=1 then remove the SingelOrDefault and you'll have a collection of the anonymous types.

您可以然后访问这样的数据:

You can then access the data like this:

query.Name
query.ShortName

等。

这篇关于如何读取XML特定的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆