[英]Read data from XML using node values in C#
我知道這個問題被問過很多次了。 但是我找不到合適的答案。
我有一個帶有一些國家代碼和國家名稱的XML文件。 這里是。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<CountryCodeNames>
<Country CountryID="0" EnglishCountryName="NOT DEFINED" ArabicCountryName="NOT DEFINED"/>
<Country CountryID="001" EnglishCountryName="ALGERIA " ArabicCountryName="الجزائر"/>
<Country CountryID="002" EnglishCountryName="ANGOLA " ArabicCountryName=" انجولا "/>
<Country CountryID="003" EnglishCountryName="BOTSWANA " ArabicCountryName=" بوتسوانا "/>
<Country CountryID="004" EnglishCountryName="BURUNDI " ArabicCountryName=" بوروندى "/>
<Country CountryID="005" EnglishCountryName="CAMERON REPUBLIC " ArabicCountryName=" جمهوريه الكمرون "/>
<Country CountryID="006" EnglishCountryName="CENTRAL AFRICAN REP. " ArabicCountryName="جمهوريهافريقياالوسطي "/>
<Country CountryID="007" EnglishCountryName="CHAD " ArabicCountryName=" تشاد "/>
<Country CountryID="008" EnglishCountryName="CONGO (BRAZZAVILLE) " ArabicCountryName=" )الكونغوا(برازافيل "/>
<Country CountryID="009" EnglishCountryName="CONGO (DRC)" ArabicCountryName="جمهورية الكنغوليس"/>
<Country CountryID="010" EnglishCountryName="BENIN (PEOPLE REPUB) " ArabicCountryName="جمهوريه بنين الشعبيه"/>
<Country CountryID="011" EnglishCountryName="ETHIOPIA " ArabicCountryName=" أثيوبيا "/>
<Country CountryID="012" EnglishCountryName="GABON " ArabicCountryName=" جمهوريه الجابون "/>
<Country CountryID="013" EnglishCountryName="GHANA " ArabicCountryName=" غانا "/>
<Country CountryID="014" EnglishCountryName="GUINEA " ArabicCountryName=" غينيا "/>
</CountryCodeNames>
現在在我的Windows窗體中,我得到了CountryID,我想根據我擁有的CountryID從此XML文件中讀取EnglishCountryName。 到目前為止,我已經嘗試過了。 對XML文件讀取了解不多。 請幫忙。
string natxmlcode = crdv4.smartcardData.NationalityCode.ToString();
XmlDocument xd = new XmlDocument();
string xmlpath = @"D:\CountriesNameList.xml";
xd.Load(xmlpath);
string nationality = xd.SelectSingleNode("CountryCodeNames/CountryID="+natxmlcode+"/EnglishCountryName").InnerText;
“ natxmlcode”是CountryID。
我建議使用XDocument; 它比XmlDocument更容易使用。
要選擇名稱,請使用以下代碼:
string natcode = crdv4.smartcardData.NationalityCode.ToString();
string xmlpath = @"D:\CountriesNameList.xml";
XDocument xd = XDocument.Load(xmlpath);
string nationality = xd.Descendants("Country")
.FirstOrDefault(c => c.Attribute("CountryID").Value.Equals(natcode))
.Attribute("EnglishCountryName").Value;
注意:您將需要System.Xml.Linq
命名空間。
Sebastian的回答確實對VS 2013有所幫助。但是我希望VS 2008中具有.Net framework 2.0的相同功能。 所以這就是我所做的並且工作正常。 感謝Sam Axe。
string xmlpath = @"D:\CountriesNameList.xml";
XmlDocument xml = new XmlDocument();
xml.Load(xmlpath);
XmlNode node = xml.SelectSingleNode("//CountryCodeNames/Country[@CountryID="+natxmlcode+"]");
string nationality = node.Attributes[1].Value.ToString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.