2012-02-10 68 views
0

如何訪問XML元素nameSur,值爲公司名稱(這是我想要的,只是[公司名稱])。我一直在收到未將對象引用設置爲對象的實例。from children in lv1.Element("IndividualName").Descendants()一行。任何意見將不勝感激。使用屬性CORPORATE訪問命名空間內的XML

static public string GetAttributeAgencyAction2(string parFileName) 
{ 
    string retVal = string.Empty; 
    XNamespace aw = "profile.information.4.0"; 
    XDocument xmlDoc = null; 

    using (StreamReader oReader = new StreamReader(parFileName, Encoding.GetEncoding("ISO-8859-1"))) 
    { 
     xmlDoc = XDocument.Load(oReader); 
    } 

    var theme = "CORPORATE"; 

    var lv1s = from lv1 in xmlDoc.Descendants(aw + "Profile") 
       where lv1.Attribute("profileType").Value.Equals(theme) 
       //where lv1.Element("IndividualName").Value == "IndividualName" 
       from children in lv1.Element("IndividualName").Descendants() 
       select new 
       { 
        Header = lv1.Attribute("profileType").Value, 
        elemento = children.Element("IndividualName").Value, 
       }; 

    //Loop through results 
    foreach (var lv1 in lv1s) 
    { 
     Console.WriteLine(lv1.Header + " "+lv1.elemento); 
     retVal = lv1.Header; 
    } 
    return retVal; 
} 

這裏是我的XML

 <Profile xmlns="profile.information.4.0" profileType="CORPORATE" gender="UNKNOWN"> 
    <creatorCode>DELPHI</creatorCode> 
    <createdDate>2012-01-24T19:35:10.000</createdDate> 
    <lastUpdaterCode>DELPHI</lastUpdaterCode> 
    <lastUpdated>2012-01-30T12:17:01.000</lastUpdated> 
    <genericName>Bonafont</genericName> 
    <IndividualName> 
     <nameSur>Company Name</nameSur> 
    </IndividualName> 
    <mfResort>5924</mfResort> 
    <mfResortProfileID>1249468</mfResortProfileID> 
    <mfContactLast>Ernert</mfContactLast> 
    <mfContactFirst>Ramillo</mfContactFirst> 
    <mfAllowMail>NO</mfAllowMail> 
    <mfAllowEMail>NO</mfAllowEMail> 
    <mfGuestPriv>NO</mfGuestPriv> 
    </Profile> 
+0

順便說一句,這不是一個有效的命名空間。它應該是一個URI。有些工具會由於命名空間不好而拒絕該文檔。 – 2012-02-10 16:53:02

回答

2

只需使用你已經定義的命名空間:

var lv1s = from lv1 in xmlDoc.Descendants(aw + "Profile") 
      where lv1.Attribute("profileType").Value.Equals(theme) 
      //where lv1.Element("IndividualName").Value == "IndividualName" 
      from child in lv1.Element(aw + "IndividualName").Descendants() 
      select new 
      { 
       Header = lv1.Attribute("profileType").Value, 
       elemento = child.Value, 
      }; 

編輯:

假設僅存在單個IndividualName元素每個Profile我會重新調整您的查詢這樣來檢查空值:

var lv1s = from lv1 in xmlDoc.Descendants(aw + "Profile") 
      where lv1.Attribute("profileType").Value.Equals(theme) && lv1.Element(aw + "IndividualName") != null 
      select new 
      { 
       Header = lv1.Attribute("profileType").Value, 
       elemento = (string)lv1.Element(aw + "IndividualName").Element(aw+"nameSur") 
      }; 
+0

感謝您的幫助。有用! – user67144 2012-02-10 17:01:36

+0

我如何驗證IndividualName和nameSur元素存在?所以我可以避免在我的代碼崩潰。 – user67144 2012-02-10 17:18:07

+0

使用替代方法更新了答案 – BrokenGlass 2012-02-10 17:34:22