2015-01-04 135 views
0

我試圖從amazon api解析XML響應。解析Amzon API * .xml響應

這是接收到的XML文件的一部分:

<BrowseNodeLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01"> 
    <OperationRequest> 
    <RequestId>31317fca-ad3d-4ff0-a64f-693c0e44959b</RequestId> 
    <Arguments> 
     <Argument Name="Operation" Value="BrowseNodeLookup" /> 
     <Argument Name="Service" Value="AWSECommerceService" /> 
     <Argument Name="Version" Value="2011-08-01" /> 
     <Argument Name="BrowseNodeId" Value="186606" /> 
     <Argument Name="Timestamp" Value="2015-01-04T11:50:06Z" /> 
     <Argument Name="ResponseGroup" Value="BrowseNodeInfo" /> 
    </Arguments> 
    <RequestProcessingTime>0.002221</RequestProcessingTime> 
    </OperationRequest> 
    <BrowseNodes> 

我想讀的爭論時間戳。這是我的代碼,但只有在刪除xml文件中的xmlns屬性時纔有效。

Dim nodeTimestamp As XmlNode = doc.SelectSingleNode("/BrowseNodeLookupResponse/OperationRequest/Arguments/Argument[@Name='Timestamp']") 

    Dim text As String = nodeTimestamp.Attributes.ItemOf("Value").InnerText 
+0

這是一個非常常見的問題。答案是使用'XmlNamespaceManager'併爲該Amazon命名空間聲明一個前綴。 – Tomalak 2015-01-04 13:23:16

回答

0

我想你收到來自亞馬遜(最後的結束標記</BrowseNodeLookupResponse>有效的XML。您可以使用LINQ2XML以選擇所需的值屬性的值,你需要採取默認的命名空間,並使用它。

' load the xml. Use XDocument.Parse to load a XML-Structure from a String! 
Dim xml as XDocument = XDocument.Load("c:\temp\axml.xml") 
' get the namespace for later use 
Dim ns = xml.Root.GetDefaultNamespace() 
' find the Arguments node, holding all Argument nodes. Note the use of the namespace 
Dim arguments = xml.Root _ 
    .Descendants(ns + "Arguments") _ 
    .Elements(ns + "Argument") 
' find and take the Argument node with the specified name 
Dim ts = from argument in arguments 
     where argument.Attribute("Name").Value = "Timestamp" 
     select argument 
' take the value of the desired attribute 
Console.WriteLine(ts.FirstOrDefault().Attribute("Value").Value) 

輸出是:

2015-01-04T11:50:06Z 
訪問和搜索在XML特定元素/節點時,對於例如我在一個叫 axml.xml文件保存在XML輸入3210

如果您想堅持使用XmlDocument方法,則需要使用XmlDocumentNamespaceManager (as shown in this SO post)以便使用名稱空間檢索節點。解決方案可能如下所示:

Dim xml = new XmlDocument() 
xml.Load("c:\temp\axml.xml") 
Dim xmlnsManager = new XmlNamespaceManager(xml.NameTable) 
' take the custom namespace and add it to the namespace manager 
xmlnsManager.AddNamespace("custom", xml.ChildNodes(0).Attributes("xmlns").Value) 
' find the desired node 
Dim nodeTimestamp = xml.SelectSingleNode("//custom:Arguments/custom:Argument[@Name='Timestamp']", xmlnsManager) 
' and take the attribute value 
Console.WriteLine(nodeTimestamp.Attributes("Value").Value) 

輸出與上面相同。

+0

感謝您的回答。我將與Linq一起嘗試,因爲我也將它用於項目中的其他事物。我想知道什麼是命名空間管理的意義,因爲我看到了亞馬遜的演示代碼。現在我知道了,我的代碼使用了命名空間管理器。 – Jimmy09 2015-01-04 12:53:33

+0

我已經添加了一個使用XmlDocument的解決方案,如您的示例中所示。 – pasty 2015-01-04 13:21:03

+0

@Tomalak感謝您的評論 - 您是嚴格的,我已經刪除了'PushScope'。關於空白前綴 - 它沒有奏效。 – pasty 2015-01-04 13:36:14