在XML中查找节点

时间:2012-03-13 15:08:56

标签: xml vb.net linq-to-xml

我有下面的代码试图在XML文档中找到IssueMaterialPO节点。我似乎无法使XPath正确或有命名空间问题。我哪里可能出错?

  Dim doc As New XmlDocument
        doc.Load(myXMLfile)

        Dim nsMgr As New XmlNamespaceManager(doc.NameTable)

        nsMgr.AddNamespace("ext_UserSchema", "http://Epicor.com/SC/UserSchema/")
        nsMgr.AddNamespace("msg", "http://Epicor.com/InternalMessage/1.1/")

        Dim nodeToFind As XmlNode
        Dim root As XmlElement = doc.DocumentElement


        nodeToFind = root.SelectSingleNode("/msg:Msg/msg:Body/msg:Req/msg:Dta/ext_UserSchema:BatchRecord/ext_UserSchema:ERP/ext_UserSchema:Transactions/ext_UserSchema:IssueMaterialPO", nsMgr)


        If (nodeToFind Is Nothing) Then
            MsgBox("Not Found")
        Else
            IMPO = True
            MsgBox("Found")
        End If

在下面的XML中找不到IssueMaterialPO

<?xml version="1.0" encoding="utf-16"?>

<msg:Msg xsi:schemaLocation="http://Epicor.com/Message/2.0      
http://scshost/schemas/epicor/ScalaMessage.xsd"   
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:msg="http://Epicor.com/Message/2.0">
<msg:Hdr>
<msg:Ctrl>
<msg:MsgID></msg:MsgID>
</msg:Ctrl>
<msg:Sender>
<msg:Name></msg:Name>
<msg:Subname></msg:Subname>
</msg:Sender>
<msg:Logon></msg:Logon>
</msg:Hdr>
<msg:Body>
<msg:Req msg-type="transaction" action="ConvertXML">
  <msg:Dta>
    <ext_UserSchema:BatchRecord xmlns:msg="http://Epicor.com/InternalMessage/1.1" 
xmlns:ext_UserSchema="http://Epicor.com/SC/UserSchema">
<ext_UserSchema:RecordNumber>11340</ext_UserSchema:RecordNumber>
      <ext_UserSchema:Date>2012-03-09</ext_UserSchema:Date>
      <ext_UserSchema:ERP>
        <ext_UserSchema:Transactions>
          <ext_UserSchema:IssueMaterialPO>
            <ext_UserSchema:Bin>BIN</ext_UserSchema:Bin>
            <ext_UserSchema:OrderNumber>555555</ext_UserSchema:OrderNumber>

            <ext_UserSchema:InventoryCategory>O</ext_UserSchema:InventoryCategory>
            <ext_UserSchema:LotNumber>678</ext_UserSchema:LotNumber>
            <ext_UserSchema:ItemNumber>12-345</ext_UserSchema:ItemNumber>
            <ext_UserSchema:Quantity>10</ext_UserSchema:Quantity>
            <ext_UserSchema:Stockroom>01</ext_UserSchema:Stockroom>
          </ext_UserSchema:IssueMaterialPO>
</ext_UserSchema:Transactions>
</ext_UserSchema:ERP>
</ext_UserSchema:BatchRecord>
</msg:Dta>
</msg:Req>
</msg:Body>
</msg:Msg>

2 个答案:

答案 0 :(得分:3)

在您使用的代码中

  

nsMgr.AddNamespace(“msg”,“http://Epicor.com/InternalMessage/1.1/”)

在您的xml文件中,命名空间为

  

的xmlns:MSG = “http://Epicor.com/Message/2.0” &GT;

在代码中更改您要求的命名空间,它应该可以正常工作。

答案 1 :(得分:0)

您的文件有

<ext_UserSchema:BatchRecord 
  xmlns:msg="http://Epicor.com/InternalMessage/1.1" 
  xmlns:ext_UserSchema="http://Epicor.com/SC/UserSchema">

但是你的Xpath使用不同的命名空间

    nsMgr.AddNamespace("ext_UserSchema", "http://Epicor.com/SC/UserSchema/")
    nsMgr.AddNamespace("msg", "http://Epicor.com/InternalMessage/1.1/")

注意尾部斜杠