2015-01-04 160 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