XML元素属性值

时间:2016-11-30 17:59:09

标签: xml xelement

我进行API调用并接收XML数据。这是样本:

> <?xml version="1.0"?> <report> <title>Employees</title> 
> <fields>
> <field name="EEID" type="int" id="id"/> <field name="Employee #"
> type="employee_number" id="employeeNumber"/> <field name="Last Name"
> type="text" id="lastName"/> <field name="First Name" type="text"
> id="firstName"/> <field name="Middle Name" type="text"
> id="middleName"/> <field name="Address Line 1" type="text"
> id="address1"/> <field name="Address Line 2" type="text"
> id="address2"/> <field name="City" type="text" id="city"/> <field
> name="Email" type="text" id="bestEmail"/> <field name="Birth Date"
> type="date" id="dateOfBirth"/> <field name="Job Title" type="list"
> id="jobTitle"/> <field name="Home Phone" type="text" id="homePhone"/>
> <field name="Work phone + ext." type="text"
> id="workPhonePlusExtension"/> <field name="Mobile Phone" type="text"
> id="mobilePhone"/> <field name="Hire Date" type="date" id="hireDate"/>
> <field name="Termination Date" type="date" id="terminationDate"/>
> </fields> 
> <data> 
> <row> <field id="id">1</field> <field
> id="employeeNumber">00-000000X</field> <field
> id="lastName">Smith</field> <field id="firstName">John</field> <field
> id="middleName"> </field> <field id="address1">1 Moon Drive, Armstrong
> Park</field> <field id="address2">PO Box 11</field> <field
> id="city">The City</field> <field
> id="bestEmail">john_smith@yahoo.com</field> <field
> id="dateOfBirth">1963-09-09</field> <field id="jobTitle">CEO</field>
> <field id="homePhone"> </field> <field
> id="workPhonePlusExtension">9</field> <field
> id="mobilePhone">976-928-0063</field> <field
> id="hireDate">1954-05-01</field> <field id="terminationDate"> </field>
> </row> 
> </data> </report>

我想使用XML / LINQ来获取一些要在datagridview中显示的字段。

我使用以下代码,但无法获取值。

 Dim xmlDoc As XDocument
 xmlDoc = XDocument.Parse(xmlstring)
 Dim query = From st In xmlDoc.Elements("report").Elements.<row>
        Select New With { _
    .employeeNumber = st.<field>.Attributes("id"), _
    .employeeFirstName = st.<field>.Attributes("firstName"), _
    .employeeLasstName = st.<field>.Attributes("lastName"), _
    .email = st.<field>.Attributes("id")}

1 个答案:

答案 0 :(得分:1)

dbasnett是正确的。 为了帮助他人,这是工作代码。

  Dim query = From st In xmlDoc.Descendants("row")
            Select New With { _
        .employeeNumber = st.<field>(1).Value, _
        .title = st.<field>(10).Value, _
        .firstName = st.<field>(2).Value, _
        .lastName = st.<field>(3).Value, _
        .address1 = st.<field>(5).Value, _
        .bestEmail = st.<field>(8).Value, _
        .dateOfBirth = st.<field>(9).Value, _
        .mobilePhone = st.<field>(13).Value}