我有以下Xml
<Main>
<Order Id="1262">
<Product>
<Name>Prod1</Name>
<Barcode>1234</Barcode>
</Product>
<Product>
<Name>Prod1</Name>
<Barcode>1234</Barcode>
</Product>
<Product>
<Name>Prod2</Name>
<Barcode>2345</Barcode>
</Product>
</Order>
<Order Id="1263">
<Product>
<Name>Prod1</Name>
<Barcode>1234</Barcode>
</Product>
<Product>
<Name>Prod1</Name>
<Barcode>1234</Barcode>
</Product>
<Product>
<Name>Prod2</Name>
<Barcode>2345</Barcode>
</Product>
</Order>
</Main>
XmlDocument xml=new XmlDocument();
xml.Load(path);
现在我只想从 orderId=1263 的节点中选择条码为 1234 的节点.我的代码是
string OrderId="1262"
string ReadedBarcode ="1234"
XmlNode ONode = xml.SelectSingleNode("//Order[@Id='" + OrderId + "']");
XmlNodeList BarCodeNodeList = ONode.SelectNodes("//Product/Barcode[text()='" + ReadedBarcode + "']");
但我不知道为什么文档中的所有节点都有内部文本 1234正在被选中。这意味着来自 <Order Id="1263"> 的偶数节点正在选择此节点。
任何解决方案?
请您参考如下方法:
应该这样做
XmlDocument xml=new XmlDocument();
xml.Load(path);
string OrderId = "1262";
string ReadedBarcode = "1234";
XmlNodeList BarCodeNodeList = xml.SelectNodes("//Order[@Id='" + OrderId + "']"+"//Product/Barcode[text()='" + ReadedBarcode + "']");
此外,您的 XML 无效,它缺少一些开始标记,应该是
<Main>
<Order Id="1262">
<Product>
<Name>Prod1</Name>
<Barcode>1234</Barcode>
</Product>
<Product>
<Name>Prod1</Name>
<Barcode>1234</Barcode>
</Product>
<Product>
<Name>Prod2</Name>
<Barcode>2345</Barcode>
</Product>
</Order>
<Order Id="1263">
<Product>
<Name>Prod1</Name>
<Barcode>1234</Barcode>
</Product>
<Product>
<Name>Prod1</Name>
<Barcode>1234</Barcode>
</Product>
<Product>
<Name>Prod2</Name>
<Barcode>2345</Barcode>
</Product>
</Order>
</Main>
