Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中解析XML字符串_Java_Xml_Parsing - Fatal编程技术网

在java中解析XML字符串

在java中解析XML字符串,java,xml,parsing,Java,Xml,Parsing,我试图解析以下字符串以获取“orderNo” String requestBody=“”; 节点列表nl=null; 试一试{ DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance(); DocumentBuilderFactory工厂=DocumentBuilderFactory.newInstance(); DocumentBuilder=factory.newDocumentBuilder(); 文档doc

我试图解析以下字符串以获取“orderNo”

String requestBody=“”;
节点列表nl=null;
试一试{
DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance();
DocumentBuilderFactory工厂=DocumentBuilderFactory.newInstance();
DocumentBuilder=factory.newDocumentBuilder();
文档doc=builder.parse(requestBody);
XPathFactory XPathFactory=XPathFactory.newInstance();
XPath=xPathfactory.newXPath();
XPathExpression expr=xpath.compile(“//ShipmentList/shipping/ShipmentLines/ShipmentLine[@OrderNo]”);
nl=(NodeList)expr.evaluate(doc,XPathConstants.NODESET);
}捕获(XPathExpressionException e1){
//TODO自动生成的捕捉块
e1.printStackTrace();
}捕获(ParserConfiguration异常e1){
//TODO自动生成的捕捉块
e1.printStackTrace();
}捕获(SAXE1异常){
//TODO自动生成的捕捉块
e1.printStackTrace();
}捕获(IOE1异常){
//TODO自动生成的捕捉块
e1.printStackTrace();
}
我尝试过使用上面的代码片段,但没有帮助 有人能告诉我有什么错误吗?

首先:
字符必须在Java字符串中转义为
\”
。requestBody字符串必须如下所示:
String requestBody=“问题从XML字符串中的未转义引号开始。然后,如何将字符串解析为
Document
对象。
Document doc=builder.parse(requestBody);
正在调用
DocumentBuilder.parse(字符串uri)
version,其中uri是要解析的XML的位置

由于有一个
字符串
要作为XML进行解析,因此必须传递
DocumentBuilder
一个
InputSource
对象,如
Document doc=builder.parse(新的InputSource(新的StringReader(requestBody));

这将使字符串进入
文档
对象

现在我们必须修复如何访问
ShipmentLine
元素中的属性
OrderNo
。要进行此更改
XPathExpression expr=xpath.compile(“//ShipmentList/ShipmentLines/ShipmentLines/ShipmentLine[@OrderNo]”;
XPathExpression expr=xpath.compile(“//ShipmentList/Shipping/ShipmentLines/ShipmentLine/@OrderNo”);
现在您应该可以得到一个
NodeList
,您可以对其进行迭代

带更改的代码
试试那样的

public static void main(String[] args) {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  DocumentBuilder builder;
  Document doc = null;
  try {
    builder = factory.newDocumentBuilder();
    doc = builder.parse("C:/shipment.xml");
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();

    try {
      XPathExpression expr = xpath.compile("/ShipmentList/Shipment/ShipmentLines/ShipmentLine");
      NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
      for (int i = 0; i < nodes.getLength(); i++) {
        Node nNode = nodes.item(i);
        System.out.println("\nCurrent Element :" + nNode.getNodeName());
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
          Element eElement = (Element) nNode;
          System.out.println("OrderNo :" + eElement.getAttribute("OrderNo"));
        }
      }
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }

  } catch (ParserConfigurationException | SAXException | IOException e) {
    e.printStackTrace();
  }

}
publicstaticvoidmain(字符串[]args){
DocumentBuilderFactory工厂=DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
文档生成器;
单据单据=空;
试一试{
builder=factory.newDocumentBuilder();
doc=builder.parse(“C:/shipping.xml”);
XPathFactory XPathFactory=XPathFactory.newInstance();
XPath=xpathFactory.newXPath();
试一试{
XPathExpression expr=xpath.compile(“/ShipmentList/Shipping/ShipmentLines/ShipmentLine”);
NodeList节点=(NodeList)expr.evaluate(doc,XPathConstants.NODESET);
对于(int i=0;i
您面临哪些问题?“我已尝试使用上述代码“上面的代码没有编译,那么您怎么可能尝试使用它呢?为了扩展@shar1er80修复的XPath问题,在原始代码中,XPath语句选择了包含OrderNo属性的ShipmentLine元素。这是因为方括号-/ShipmentLine[@OrderNo]-正在定义一个过滤器。改为使用路径步骤-/ShipmentLine/@OrderNo-意味着您现在正在从ShipmentLine元素中选择OrderNo属性。@RajgauriKhemnar如果我的答案解决了您的问题,请检查,以便将您的问题标记为已回答。
Document doc = builder.parse(new ByteArrayInputStream(requestBody.getBytes()));
import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class StackOverflow {
    public static void main(String[] args) {
        String requestBody = 
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
                + "<ShipmentList>"
                + "<Shipment ActualShipmentDate=\"2018-06-26T11:25:00+05:30\" DocumentType=\"0005\" TotalWeight=\"55.5\" TotalWeightUOM=\"LB\" TrackingNo=\"9461236897846412938163\">"
                + "<ShipmentLines>"
                + "<ShipmentLine OrderNo=\"1529904772887\" PrimeLineNo=\"1\" Quantity=\"3\" SubLineNo=\"1\"/>"
                + "<ShipmentLine OrderNo=\"1529904772887\" PrimeLineNo=\"2\" Quantity=\"3\" SubLineNo=\"1\"/>"
                + "<ShipmentLine OrderNo=\"1529904772887\" PrimeLineNo=\"3\" Quantity=\"3\" SubLineNo=\"1\"/>"
                + "<ShipmentLine OrderNo=\"1529904772887\" PrimeLineNo=\"4\" Quantity=\"3\" SubLineNo=\"1\"/>"
                + "<ShipmentLine OrderNo=\"1529904772887\" PrimeLineNo=\"5\" Quantity=\"3\" SubLineNo=\"1\"/>"
                + "</ShipmentLines>"
                + "<Extn ExtnPackageASN=\"55538770655551006451\" ExtnPackageID=\"6247442951596360944\" ExtnPackLength=\"25.0\" ExtnLengthUOM=\"IN\" ExtnPackWidth=\"20.0\" ExtnWidthUOM=\"IN\" ExtnPackHeight=\"16.0\" ExtnHeightUOM=\"IN\" ExtnCarrierMethodId=\"83\"/>"
                + "</Shipment>"
                + "</ShipmentList>";

        NodeList nl = null;
        try {
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(requestBody)));
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression expr = xpath.compile("//ShipmentList/Shipment/ShipmentLines/ShipmentLine/@OrderNo");
            nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

            // Output NodeList
            for (int i = 0; i < nl.getLength(); i++) {
                System.out.println(nl.item(i));
            }
        } catch (XPathExpressionException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ParserConfigurationException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (SAXException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}
OrderNo="1529904772887"
OrderNo="1529904772887"
OrderNo="1529904772887"
OrderNo="1529904772887"
OrderNo="1529904772887"
public static void main(String[] args) {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  DocumentBuilder builder;
  Document doc = null;
  try {
    builder = factory.newDocumentBuilder();
    doc = builder.parse("C:/shipment.xml");
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();

    try {
      XPathExpression expr = xpath.compile("/ShipmentList/Shipment/ShipmentLines/ShipmentLine");
      NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
      for (int i = 0; i < nodes.getLength(); i++) {
        Node nNode = nodes.item(i);
        System.out.println("\nCurrent Element :" + nNode.getNodeName());
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
          Element eElement = (Element) nNode;
          System.out.println("OrderNo :" + eElement.getAttribute("OrderNo"));
        }
      }
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }

  } catch (ParserConfigurationException | SAXException | IOException e) {
    e.printStackTrace();
  }

}