2016-05-31 70 views
0

我有一個看起來像這樣爲什麼我沒有得到的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; 

我不是爲元素獲取值的XML。例如,FullName的值應該是「Tommy SOP_NBR61553」。但是我看到這個字符串值

我在做什麼錯在這裏

+0

我不是專家,但是,豈不是這條線?對我來說,它看起來像你只叫第一個名字? - >'var FullName = First_Name +「」id;'它不會像'var FullName = First_Name + Middle_Name + Last_Name「」id;' ? – 2016-05-31 15:32:17

回答

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"); 
+0

謝謝@Martin Honnen解決了這個問題 – Perry

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;