如何使用XMLReader解析XML文档?

时间:2013-12-10 20:52:12

标签: c# parsing xmlreader

这是我的XML:

http://simon.ist.rit.edu:8080/Services/resources/ESD/OrgTypes/

我希望能够在“类型”下抓取这些键盘并忽略这些数字。

如医师,救护车等

<data>
<row>
<typeId>0</typeId>
<type>Physician</type>
</row>
<row>
<typeId>1</typeId>
<type>Ambulance</type>
</row>
<row>
<typeId>2</typeId>
<type>Fire Department</type>
</row>
<row>
<typeId>3</typeId>
<type>Helicopter/Air Transport</type>
</row>
</data>

我如何在C#中做到这一点?

2 个答案:

答案 0 :(得分:4)

var types = XDocument.Load("http://simon.ist.rit.edu:8080/Services/resources/ESD/OrgTypes/")
                .Descendants("type")
                .Select(t => (string)t)
                .ToList();

答案 1 :(得分:1)

这个方法真的不完整,值得初学者解释一下C#和LINQ-to-XML:

var types = XDocument.Load("http://simon.ist.rit.edu:8080/Services/resources/ESD/OrgTypes/")
                .Descendants("type")
                .Select(t => (string)t) // under the hood magic
                .ToList();

使用(string)进行投射有点神奇,如果使用ToString()则不会得到相同的结果。我将解释......我对XML进行了一些修改:

<type attrib="bar" attrib2="boo" >Resource
    <foo a="1" a.2="A"/>
</type>
// note, I also removed the value of type immediately following Resource node

(string)上的t广告在t.Value的幕后操作。没有演员表,结果是:

<type>Physician</type>  
<type>Ambulance</type>  
<type>Fire Department</type>  
<type>Helicopter/Air Transport</type>  
<type>Home Care Agency</type>  
<type>Hospital</type>  
<type>Law Enforcement Agency</type>  
<type>Nursing Home</type>
<type attrib="bar" attrib2="boo">Resource  
                <foo a="1" a.2="A" /></type>  
<type></type>  
<type>Other</type>  
<type>Hospice</type>  
<type>School</type>  
<type>Emergency Shelter</type>  

使用(string)t

Physician
Ambulance
Fire Department
Helicopter/Air Transport
Home Care Agency
Hospital
Law Enforcement Agency
Nursing Home
Resource


Other
Hospice
School
Emergency Shelter

t.Value

Physician
Ambulance
Fire Department
Helicopter/Air Transport
Home Care Agency
Hospital
Law Enforcement Agency
Nursing Home
Resource


Other
Hospice
School
Emergency Shelter

最后,要表明t.ToString()(string)t不同:

<type>Physician</type>
<type>Ambulance</type>
<type>Fire Department</type>
<type>Helicopter/Air Transport</type>
<type>Home Care Agency</type>
<type>Hospital</type>
<type>Law Enforcement Agency</type>
<type>Nursing Home</type>
<type attrib="bar" attrib2="boo">Resource
                <foo a="1" a.2="A" /></type>
<type></type>
<type>Other</type>
<type>Hospice</type>
<type>School</type>
<type>Emergency Shelter</type>

所有这一切都是为了重复使用LINQ-to-XML的一些鲜为人知的问题

我对清晰度和易维护性的建议如下:

var types = XDocument.Load("http://simon.ist.rit.edu:8080/Services/resources/ESD/OrgTypes/")
                .Descendants("type")
                .Select(t => t.Value) // be explicit about what you want
                .ToList();

您可以搜索IEnumerable风格的任何elementdescendant