我有一个看起来像这样的XML
<Registered id="SOP_NBR61553">
<RoleOfPerson>
<PersonBirthDate>
<Date>1970-08-11</Date>
</PersonBirthDate>
<PersonName>
<PersonGivenName>TOMMY</PersonGivenName>
<PersonMiddleName/>
<PersonSurName>SMITH</PersonSurName>
<PersonNameSuffixText/>
</PersonName>
<PersonRaceCode>B</PersonRaceCode>
<PersonSexCode>M</PersonSexCode>
</RoleOfPerson>
</Registered>
当我运行此代码时
var id = custOrd.Element("Registered").Attribute("id");
var BirthDate = custOrd.Element("Registered").Element("RoleOfPerson").Element("PersonBirthDate").Element("Date");
var First_Name = custOrd.Element("Registered").Element("RoleOfPerson").Element("PersonName").Element("PersonGivenName");
var Middle_Name = custOrd.Element("Registered").Element("RoleOfPerson").Element("PersonName").Element("PersonMiddleName");
var Last_Name = custOrd.Element("Registered").Element("RoleOfPerson").Element("PersonName").Element("PersonSurName");
var Race = custOrd.Element("Registered").Element("RoleOfPerson").Element("PersonRaceCode");
var Sex = custOrd.Element("Registered").Element("RoleOfPerson").Element("PersonSexCode");
var FullName = First_Name +" "id;
我没有得到元素的值。例如,FullName的值应为&#34; Tommy SOP_NBR61553&#34;。但是我看到了这个字符串值
<PersonGivenName>TOMMY</PersonGivenName> id="SOP_NBR61553"
我在这里做错了什么
答案 0 :(得分:1)
如果这是使用LINQ to XML的C#代码,那么不要像现在那样选择属性或元素节点,而是确保提取字符串值,最好用例如。
var id = (string)custOrd.Element("Registered").Attribute("id");
var First_Name = (string)custOrd.Element("Registered").Element("RoleOfPerson").Element("PersonName").Element("PersonGivenName");
答案 1 :(得分:0)
尝试(.Value属性),如:
var id = custOrd.Element("Registered").Attribute("id").Value;
var First_Name = custOrd.Element("Registered").Element("RoleOfPerson").Element("PersonName").Element("PersonGivenName").Value;
var Middle_Name = custOrd.Element("Registered").Element("RoleOfPerson").Element("PersonName").Element("PersonMiddleName").Value;
最后一行也是一个小改动:
var FullName = First_Name +" "+ id;