簡體   English   中英

從XML文件讀取Node屬性

[英]Read Node attributes from XML file

我有以下XML文件。

<?xml version="1.0" encoding="utf-8" ?>
<Countries>
    <Country>
        <Id>101</Id>
        <City>Austin</City>
    </Country>
    <Country>
        <Id>102</Id>
        <City>Dallas</City>
    </Country>
    <Country>
        <Id>103</Id>
        <City>Chicago</City>
    </Country>
    <Country>
        <Id>104</Id>
        <City>Aman</City>
     </Country>
</Countries>

我正在嘗試從后面的代碼中讀取它。 這是代碼

List<City> cityList = new List<City>();
string url = "/App_Data/Countries.xml";
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath(url));
XmlNodeList nodeList = doc.SelectNodes("Country");
foreach (XmlNode node in nodeList)
{
    if (node != null)
    {                        
        int id = int.Parse(node.Attributes["Country"].Value);
        string name = node.Attributes["City"].Value;
        City city = new City(id, name);
        cityList.Add(city);
    }
}

由於某種原因,下面的代碼

XmlNodeList nodeList = doc.SelectNodes("Country");

完全不返回任何節點。

根據https://msdn.microsoft.com/zh-cn/library/hcebdtae(v=vs.110).aspx ,這是SelectNodes方法的作用

選擇與XPath表達式匹配的節點列表。

既然你這樣

XmlNodeList nodeList = doc.SelectNodes("Country");

您正在當前上下文中選擇所有<Country>元素(即根),但是<Country>元素實際上位於<Countries>內部,因此這就是為什么根本沒有節點的原因。 將上面的語法更改為此

XmlNodeList nodeList = doc.SelectNodes("Countries/Country");

這是有關XPath表達式示例的更多信息: https : //msdn.microsoft.com/zh-cn/library/ms256086%28v=vs.110%29.aspx

如果您的目標是.NET 3.5或更高版本,則應考慮使用XDocument API而不是XmlDocument API(請參閱XDocument或XMLDocument )。


對於您的情況,實現如下所示:

var cityList = new List<City>();            
XDocument xDoc = XDocument.Load(Server.MapPath("/App_Data/Countries.xml"));
foreach (XElement xCountry in xDoc.Root.Elements())
{
    int id = int.Parse(xCountry.Element("Id").Value);
    string name = xCountry.Element("City").Value;                
    cityList.Add(new City(id, name));
}

謝謝你們。 想通了。 這是更新的代碼。 但是我認為必須有比我做的更好的填充對象的方法。

  List<City> cityList = new List<City>();
            string url ="/App_Data/Countries.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath(url));
            XmlNodeList nodeList = doc.SelectNodes("//Country");
            foreach(XmlNode node in nodeList){
                if (node != null)
                {                        
                    int id = int.Parse(node.ChildNodes.Item(0).InnerText);
                    string name = node.ChildNodes.Item(1).InnerText;
                    City city = new City(id,name);
                    cityList.Add(city);
                }
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM