我想读取所有元素以及具有一些值ValueID字段的元素。请指导我如何在C#中执行此操作,因为我正在使用DataSet来读取XML。
以下是我需要执行上述任务的XML ...
<?xml version="1.0" encoding="utf-8"?>
<Jobs>
<Job Action="Post">
<AdvertiserName>University of Missouri - St. Louis</AdvertiserName>
<AdvertiserType ValueID="15890">Agency</AdvertiserType>
<Classification ValueID="6215">I.T. & Communications</Classification>
<SubClassification></SubClassification>
<Country ValueID="247">United States</Country>
<Location ValueID="15346">Missouri</Location>
<Area ValueID="38701">Saint Louis </Area>
<PostalCode>63121</PostalCode>
<Language ValueID="120036">2057</Language>
<ContactName>
</ContactName>
<EmploymentType ValueID="2163">Permanent</EmploymentType>
<StartDate>2014-02-23T06:01:55.907</StartDate>
<Duration></Duration>
</Job>
</Jobs>
答案 0 :(得分:0)
正如我在评论中所说,请查看XDocument
以处理C#中的XML。例如:
var doc = XDocument.Load("path_to_xml_file.xml");
//or if you have XML string instead of file :
//var doc = XDocument.Parse("xml string here");
var elements = doc
//<Jobs>
.Root
//<Job>
.Element("Job")
//all element that is direct child of <Job>
.Elements();
foreach (var element in elements)
{
//get current element name
var name = element.Name.LocalName;
//get text inside current element tag
var value = element.Value;
if(element.Attribute("ValueID") != null)
{
//get value of ValueID attribute
var valueId = element.Attribute("ValueID").Value;
Console.WriteLine("element name : {0}. Value = {1}. ValueID = {2}", name, value, valueId);
}
else
{
Console.WriteLine("element name : {0}. Value = {1}.", name, value);
}
}