2011-03-02 22 views
0

我有一個在.net 2.0上的應用程序,我對它有一些困難,因爲我更習慣於linq。使用.net2.0計算元素和讀取屬性?

的XML文件是這樣的:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<updates> 
    <files> 
     <file url="files/filename.ext" checksum="06B9EEA618EEFF53D0E9B97C33C4D3DE3492E086" folder="bin" system="0" size="40448" /> 
     <file url="files/filename.ext" checksum="CA8078D1FDCBD589D3769D293014154B8854D6A9" folder="" system="0" size="216" /> 
     <file url="files/filename.ext" checksum="CA8078D1FDCBD589D3769D293014154B8854D6A9" folder="" system="0" size="216" /> 
    </files> 
</updates> 

文件被下載並readed上飛:

XmlDocument readXML = new XmlDocument(); 
readXML.LoadXml(xmlData); 

起初,我以爲它會像這樣的東西去:

XmlElement root = doc.DocumentElement; 
XmlNodeList nodes = root.SelectNodes("//files"); 

foreach (XmlNode node in nodes) 
{ 
... im reading it ... 
} 

但在閱讀它們之前,我需要知道它們在我的進度條上有多少使用,而我是als o在這種情況下,如何獲取文件元素的屬性無能爲力。

  • 我怎麼能算多少「文件」 ELEMENTS我有(進入的foreach OFC之前指望他們)和閱讀他們的 屬性?

我需要計數,因爲它將用於更新進度條。

總的來說,它並沒有很好地閱讀我的xml。

回答

2

閱讀它們之前,我需要知道如何很多他們在我的進度條上使用

使用XmlNodeList.Count財產。下面的代碼示例。

整體而言,這是不讀我的XML很好

這裏有讀取XML與舊XML庫的一些技巧。

首先,XPath是你的朋友。它使您能夠以非常類似於Linq的方式非常快速地查詢元素。在這種情況下,您應該更改XPath以獲取子文件元素列表,而不是父文件元素。

XmlNodeList nodes = root.SelectNodes("//files"); 

變爲

XmlNodeList files = root.SelectNodes("//file"); 

//ElementName遞歸搜索與該名稱的所有元素。 XPath非常酷,你應該閱讀一下。這裏有一些鏈接:

一旦你有了這些元素,你可以使用XmlElement.Attributes屬性,再加上XmlAttribute.Value屬性(file.Attributes["url"].Value)。

或者您可以使用GetAttribute方法。

Click this link to the documentation on XmlElement欲瞭解更多信息。請記住在該頁面上將.Net Framework版本切換爲2.0。

XmlElement root = doc.DocumentElement; 
XmlNodeList files = root.SelectNodes("//file"); // file element, not files element 

int numberOfFiles = files.Count; 
// Todo: Update progress bar here 

foreach (XmlElement file in files) // These are elements, so this cast is safe-ish 
{ 
    string url = file.GetAttribute("url"); 
    string folder = file.GetAttribute("folder"); 

    // If not an integer, will throw. Could use int.TryParse instead 
    int system = int.Parse(file.GetAttribute("system")); 
    int size = int.Parse(file.GetAttribute("size")); 

    // convert this to a byte array later 
    string checksum = file.GetAttribute("checksum"); 
} 

關於如何將校驗轉換成字節數組,看這個問題:

How can I convert a hex string to a byte array?

+0

我真的很感謝你的回覆和時間,它涵蓋了我所有的疑惑,並且還有更多的簡單易懂的例子和指向一些有趣的文檔,你甚至花時間表明我可以使用int.Parse或int.TryParse,謝謝非常。 – Prix 2011-03-02 05:59:37

+0

@Prix:沒問題。你也可以看看Xml序列化來做到這一點,這是我建議的解決方案,但這更加複雜:) – 2011-03-02 23:16:45

+0

我實際上正在研究它,使它工作是第一步嘿,我其實是想要序列化它從一開始,但由於我做得不好,我來請求一些備份ehhehe;) – Prix 2011-03-03 00:16:42

0

編輯:

,你應該能夠使用nodes[0].ChildNodes.Count;

+0

他需要在XML我覺得節點的總數和'node.ChildNodes.Count ()'只會帶來任何給定節點的直接子節點的數量。 – PedroC88 2011-03-02 04:59:49

+0

@ PedroC88根據建議編輯。 – 2011-03-02 05:04:26

0

你可以讓你的集合的長度計算的一些要素:

int ElementsCount = nodes.Count; 

可以讀取屬性如下:

foreach(XmlNode node in nodes) { 
    Console.WriteLine("Value: " + node.Attributes["name_of_attribute"].Value; 
}