2014-03-06 79 views
1

我目前正在將一個Java編寫的XML解析器移植到C#中。 Java中的解析器是幾個月前由我編寫的(雖然現在很大程度上已經放棄了,因爲我們的公司轉移到了C#爲我們的項目),通過URL解析XML數據,尤其是this(具有自定義經緯度/時間參數)。Java XML XPath解析器到C#

對於Java解析器,我選擇了XPath,因爲數據很亂。因此,定義我的自定義路徑而不是迭代並保存每一個項目是我所做的。在Java中

代碼段中的問題我有一些問題,在移植是:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
DocumentBuilder db = dbf.newDocumentBuilder(); 
Document doc = db.parse(someURLToXML.openStream()); 

XPathFactory xPathfactory = XPathFactory.newInstance(); 
XPath xpath = xPathfactory.newXPath(); 

XPathExpression hourly = xpath.compile("/dwml/data/time-layout[3]/start-valid-time/text()"); 
XPathExpression tempHourly = xpath.compile("/dwml/data/parameters/temperature[@type='hourly']/value/text()"); 

NodeList hourlyResult = (NodeList) hourly.evaluate(doc,XPathConstants.NODESET); 
NodeList tempHourlyResult = (NodeList) tempHourly.evaluate(doc,XPathConstants.NODESET); 

閱讀C#XPath的腳本一些教程,我碰到這個site。另外谷歌搜索似乎這是在C#上執行XPath的事實上的方式。

我有這個在我的C#骨架至今:

XmlTextReader reader = new XmlTextReader(URL); 

XPathDocument doc = new XPathDocument(reader); 
XPathNavigator nav = doc.CreateNavigator(); 

XPathExpression expr; 
expr = nav.Compile("/dwml/data/"); 
XPathNodeIterator iterator = nav.Select(expr); 

while (iterator.MoveNext()) 
{ 
    // do something 
} 

我所做的是我確定我的默認表情在expr,但在那之後,我不是很清楚如何端口我上面的XPaths從Java腳本到While循環,或者即使我需要它,因爲我原來的腳本根本沒有使用任何循環,因爲不需要使用XML遍歷的硬編碼。

我的問題是,我該怎麼辦端口四行:

XPathExpression hourly = xpath.compile("/dwml/data/time-layout[3]/start-valid-time/text()"); 
XPathExpression tempHourly = xpath.compile("/dwml/data/parameters/temperature[@type='hourly']/value/text()"); 

NodeList hourlyResult = (NodeList) hourly.evaluate(doc,XPathConstants.NODESET); 
NodeList tempHourlyResult = (NodeList) tempHourly.evaluate(doc,XPathConstants.NODESET); 

到C#?

編輯:

嘗試這樣的:

XmlTextReader reader = new XmlTextReader(URL); 

XPathDocument doc = new XPathDocument(reader); 
XPathNavigator nav = doc.CreateNavigator(); 

foreach(XPathNavigator node in (XPathNodeIterator) nav.Evaluate("/dwml/data/time-layout[3]/start-valid-time/text()")) 
{ 
    hourly.Add(node.Value); 
} 

回答

1

下面的代碼讓我保留我的XPath規則,仍然做我想做的,並且在好的方面,它增加值到一個字符串列表 - 很好!

XmlTextReader reader = new XmlTextReader(URL); 

XPathDocument doc = new XPathDocument(reader); 
XPathNavigator nav = doc.CreateNavigator(); 

List<string> hourly = new List<string>(); 

foreach(XPathNavigator node in (XPathNodeIterator) nav.Evaluate("/dwml/data/time-layout[3]/start-valid-time/text()")) 
{ 
    hourly.Add(node.Value); 
} 
+0

搞笑你是自我恭維:) –

+0

從微軟的XML團隊下面的博客文章指出,'XmlTextReader'已過時,不應使用。應該使用'XmlReader'來代替。博客文章:https://blogs.msdn.microsoft.com/xmlteam/2011/10/08/the-world-has-moved-on-have-you-xml-apis-you-should-avoid-using/ –