Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/335.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 获取不同级别中具有相同名称的所有节点_Java_Xml_Jdom_Xmlnode - Fatal编程技术网

Java 获取不同级别中具有相同名称的所有节点

Java 获取不同级别中具有相同名称的所有节点,java,xml,jdom,xmlnode,Java,Xml,Jdom,Xmlnode,以下是我的XML文件: <scenario> <negotiation> <type>auction</type> <agent> <type>UtilityCompany</type> <electricityPlan> <type>PlanUtility</type> <offeredEne

以下是我的XML文件:

<scenario>
  <negotiation>
    <type>auction</type>

    <agent>
      <type>UtilityCompany</type>
      <electricityPlan>
        <type>PlanUtility</type>
        <offeredEnergy>10</offeredEnergy>
        <duration>20</duration>
        <price>10</price>
        <role>
          <type>Seller</type>
        </role>
        <electricityOrder>
          <type>SalesOrder</type>
        </electricityOrder>
      </electricityPlan>
    </agent>

    <agent>
      <type>LargeCustomer</type>
      <electricityPlan>
        <type>LargecPlan</type>
        <requestedEnergy>100</requestedEnergy>
        <duration>20</duration>
        <price>10</price>
        <role>
          <type>Buyer</type>
        </role>
        <electricityOrder>
          <type>PurchaseOrder</type>
        </electricityOrder>
      </electricityPlan>
    </agent>

  </negotiation>
</scenario>
有人能提供一些见解吗

更新信息

目前,我有以下几点:

公共静态void main(字符串[]args)抛出ParserConfiguration异常、SAXException、IOException、XPathExpressionException{

    File fXmlFile = new File("scenario.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);

    NodeList nodes = doc.getElementsByTagName("negotiation");
    Element element = (Element) nodes.item(0);
    NodeList negotiationList = element.getElementsByTagName("agent");
    for (int i = 0; i < negotiationList.getLength(); i++) {

    Element negotiationElement = (Element) negotiationList.item(i);


NodeList agent = negotiationElement.getElementsByTagName("type");
System.out.println(agent.item(0).getFirstChild().getTextContent());

NodeList role = negotiationElement.getElementsByTagName("role");
Element roleline = (Element) role.item(0);
System.out.println(roleline.getElementsByTagName("type").item(0).getTextContent());
大客户 买主

但我不知道如何从中获取值

      1.         <type>auction</type>

      2. <type>PlanUtility</type>  from ElectricityPlan tag.
1.拍卖
2.电气计划标签中的计划实用程序。
最后,我找到了一个解决方案:

 public class ReadingXML {

static List<String> AuctionType = new ArrayList<String>();
static List<String> AgentType = new ArrayList<String>();
static List<String> PlanType = new ArrayList<String>();
static List<String> RoleType = new ArrayList<String>();
static List<String> OrderType = new ArrayList<String>();
static NodeList auction ;

 public List<List<String>> ReadingXML(String fileLocation) throws      
 ParserConfigurationException, SAXException, IOException {

//File fXmlFile = new File("C:....location\\scenario.xml");

File fXmlFile = new File(fileLocation);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
List<List<String>> listOfLists = Lists.newArrayList();

    NodeList nodesScenario = doc.getElementsByTagName("scenario");
    Element element0 = (Element) nodesScenario.item(0);
    NodeList scenarioList = element0.getElementsByTagName("negotiation");

   for (int j = 0; j < scenarioList.getLength(); j++) 
     {
       Element scenarioElement = (Element) scenarioList.item(j);
       auction = scenarioElement.getElementsByTagName("type");
       System.out.println(auction.item(0).getFirstChild().getTextContent());
       AuctionType.add(auction.item(0).getFirstChild().getTextContent()); 
     }
    List<String> AuctionTypeFiltered = Lists.newArrayList(Sets.newHashSet(AuctionType));
    listOfLists.add(Lists.newArrayList(AuctionTypeFiltered));

NodeList nodesNegotiation = doc.getElementsByTagName("negotiation");
Element element = (Element) nodesNegotiation.item(0);
NodeList negotiationList = element.getElementsByTagName("agent"); 

for (int i = 0; i < negotiationList.getLength(); i++) 
 {
   Element negotiationElement = (Element) negotiationList.item(i);
   NodeList agent = negotiationElement.getElementsByTagName("type");
   System.out.println(agent.item(0).getFirstChild().getTextContent());
   AgentType.add(agent.item(0).getFirstChild().getTextContent());

   NodeList nodesElectricityPlan = doc.getElementsByTagName("electricityPlan");
   Element element1 = (Element) nodesElectricityPlan.item(0);
   NodeList ElectricityPlanList = element1.getElementsByTagName("plan");

   for (int j = 0; j < ElectricityPlanList.getLength(); j++) 
    {
      Element electricityPlanElement = (Element) ElectricityPlanList.item(j);
      NodeList plan = electricityPlanElement.getElementsByTagName("type");
      System.out.println(plan.item(0).getFirstChild().getTextContent());
      PlanType.add(plan.item(0).getFirstChild().getTextContent());
    } 
    List<String> PlanTypeFiltered = Lists.newArrayList(Sets.newHashSet(PlanType));
    listOfLists.add(Lists.newArrayList(PlanTypeFiltered));

    NodeList role = negotiationElement.getElementsByTagName("role");
    Element roleline = (Element) role.item(0);
    System.out.println(roleline.getElementsByTagName("type").item(0).getTextContent());
    RoleType.add(roleline.getElementsByTagName("type").item(0).getTextContent());

    NodeList electricityorder = negotiationElement.getElementsByTagName("electricityOrder");
    Element electricityorderline = (Element) electricityorder.item(0);
    System.out.println(electricityorderline.getElementsByTagName("type").item(0).getTextContent());
    OrderType.add(electricityorderline.getElementsByTagName("type").item(0).getTextContent());
  }
   List<String> AgentTypeFiltered = Lists.newArrayList(Sets.newHashSet(AgentType));
   listOfLists.add(Lists.newArrayList(AgentTypeFiltered));

   List<String> RoleTypeFiltered = Lists.newArrayList(Sets.newHashSet(RoleType));
   listOfLists.add(Lists.newArrayList(RoleTypeFiltered));

   List<String> OrderTypeFiltered = Lists.newArrayList(Sets.newHashSet(OrderType));
   listOfLists.add(Lists.newArrayList(OrderTypeFiltered));

    return listOfLists;
    }



  } 
此代码用于获取请求的节点

我有一个解决方案:

 public class ReadingXML {

static List<String> AuctionType = new ArrayList<String>();
static List<String> AgentType = new ArrayList<String>();
static List<String> PlanType = new ArrayList<String>();
static List<String> RoleType = new ArrayList<String>();
static List<String> OrderType = new ArrayList<String>();
static NodeList auction ;

 public List<List<String>> ReadingXML(String fileLocation) throws      
 ParserConfigurationException, SAXException, IOException {

//File fXmlFile = new File("C:....location\\scenario.xml");

File fXmlFile = new File(fileLocation);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
List<List<String>> listOfLists = Lists.newArrayList();

    NodeList nodesScenario = doc.getElementsByTagName("scenario");
    Element element0 = (Element) nodesScenario.item(0);
    NodeList scenarioList = element0.getElementsByTagName("negotiation");

   for (int j = 0; j < scenarioList.getLength(); j++) 
     {
       Element scenarioElement = (Element) scenarioList.item(j);
       auction = scenarioElement.getElementsByTagName("type");
       System.out.println(auction.item(0).getFirstChild().getTextContent());
       AuctionType.add(auction.item(0).getFirstChild().getTextContent()); 
     }
    List<String> AuctionTypeFiltered = Lists.newArrayList(Sets.newHashSet(AuctionType));
    listOfLists.add(Lists.newArrayList(AuctionTypeFiltered));

NodeList nodesNegotiation = doc.getElementsByTagName("negotiation");
Element element = (Element) nodesNegotiation.item(0);
NodeList negotiationList = element.getElementsByTagName("agent"); 

for (int i = 0; i < negotiationList.getLength(); i++) 
 {
   Element negotiationElement = (Element) negotiationList.item(i);
   NodeList agent = negotiationElement.getElementsByTagName("type");
   System.out.println(agent.item(0).getFirstChild().getTextContent());
   AgentType.add(agent.item(0).getFirstChild().getTextContent());

   NodeList nodesElectricityPlan = doc.getElementsByTagName("electricityPlan");
   Element element1 = (Element) nodesElectricityPlan.item(0);
   NodeList ElectricityPlanList = element1.getElementsByTagName("plan");

   for (int j = 0; j < ElectricityPlanList.getLength(); j++) 
    {
      Element electricityPlanElement = (Element) ElectricityPlanList.item(j);
      NodeList plan = electricityPlanElement.getElementsByTagName("type");
      System.out.println(plan.item(0).getFirstChild().getTextContent());
      PlanType.add(plan.item(0).getFirstChild().getTextContent());
    } 
    List<String> PlanTypeFiltered = Lists.newArrayList(Sets.newHashSet(PlanType));
    listOfLists.add(Lists.newArrayList(PlanTypeFiltered));

    NodeList role = negotiationElement.getElementsByTagName("role");
    Element roleline = (Element) role.item(0);
    System.out.println(roleline.getElementsByTagName("type").item(0).getTextContent());
    RoleType.add(roleline.getElementsByTagName("type").item(0).getTextContent());

    NodeList electricityorder = negotiationElement.getElementsByTagName("electricityOrder");
    Element electricityorderline = (Element) electricityorder.item(0);
    System.out.println(electricityorderline.getElementsByTagName("type").item(0).getTextContent());
    OrderType.add(electricityorderline.getElementsByTagName("type").item(0).getTextContent());
  }
   List<String> AgentTypeFiltered = Lists.newArrayList(Sets.newHashSet(AgentType));
   listOfLists.add(Lists.newArrayList(AgentTypeFiltered));

   List<String> RoleTypeFiltered = Lists.newArrayList(Sets.newHashSet(RoleType));
   listOfLists.add(Lists.newArrayList(RoleTypeFiltered));

   List<String> OrderTypeFiltered = Lists.newArrayList(Sets.newHashSet(OrderType));
   listOfLists.add(Lists.newArrayList(OrderTypeFiltered));

    return listOfLists;
    }



  } 
公共类读取XML{
静态列表AuctionType=new ArrayList();
静态列表AgentType=new ArrayList();
静态列表PlanType=newarraylist();
静态列表RoleType=newarraylist();
静态列表OrderType=new ArrayList();
静态节点拍卖;
公共列表读取XML(字符串文件位置)抛出
ParserConfiguration异常、SAXException、IOException{
//File fXmlFile=新文件(“C:..location\\scenario.xml”);
File fXmlFile=新文件(fileLocation);
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder=dbFactory.newDocumentBuilder();
documentdoc=dBuilder.parse(fXmlFile);
List listOfLists=Lists.newArrayList();
NodeList nodesScenario=doc.getElementsByTagName(“场景”);
Element element0=(Element)nodesScenario.item(0);
NodeList scenarioList=element0.getElementsByTagName(“协商”);
对于(int j=0;j

而不是对每种类型都有一个<代码> ARAYLIST/<代码>考虑采用面向对象(OO)的方法。您将注意到这种方法的许多优点,例如(很多)更少的变量和代码行。

Agent[0] = UtilityCompany
Agent[1] = LargeCustomer

electricityPlan[0] = PlanUtility
electricityPlan[1] = LargecPlan

role[0] = Seller
role[1] = Buyer
Agent
  AuctionType: 
    AgentType: UtilityCompany
     RoleType: Seller
     PlanType: PlanUtility
    OrderType: SalesOrder
Agent
  AuctionType: 
    AgentType: LargeCustomer
     RoleType: Buyer
     PlanType: LargecPlan
    OrderType: PurchaseOrder
Driver.java:

public class Driver {
    public static final String XML_FILE_PATH = "zin/zin.xml";

    /**
     * Entry point of the program.
     */
    public static void main(String[] args) throws IOException, JDOMException {
        File xmlFile = new File(XML_FILE_PATH);
        // the SAXBuilder is the easiest way to create the JDOM2 objects
        SAXBuilder jdomBuilder = new SAXBuilder();

        // jdomDocument is the JDOM2 Object
        Document jdomDocument = jdomBuilder.build(xmlFile);
        Element root = jdomDocument.getRootElement();
        Element negotiation = root.getChild("negotiation");

        // get the list of children agent elements
        List<Element> xmlAgents = negotiation.getChildren("agent");
        // list for holding the agent objects parsed from the XML file
        List<Agent> agents = new ArrayList<Agent>();

        // iterate over the agent nodes from the XML file and create
        // agent objects to represent them
        for (Element currentAgent : xmlAgents) {
            Agent newAgent = new Agent();
            // set the new agent's 'AgentType' before descending into
            // the children XML nodes
            newAgent.setAgentType(currentAgent.getChildText("type"));

            // recursively finish the new agent
            descend(currentAgent, newAgent);

            // add the new agent to the ArrayList of agents
            agents.add(newAgent);
        }

        // print agent data to output
        for(Agent agent : agents) {
            System.out.println(agent);
        }
    }

    /**
     * Note: Agent is not immutable, this method alters the members
     * of the passed in Agent object.
     * 
     * Recursive method to fill in the rest of a passed in Agent object.
     * 
     * @param ele - an XML element to descend.
     * @param agent - the Agent object to finish filling.
     */
    public static void descend(Element ele, Agent agent) {
        for (Element e : ele.getChildren()) {
            switch (e.getName()) {
                case "electricityPlan":
                    agent.setPlanType(e.getChildText("type"));
                    break;
                case "role":
                    agent.setRoleType(e.getChildText("type"));
                    break;
                case "electricityOrder":
                    agent.setOrderType(e.getChildText("type"));
                    break;
                default:
                    break;
            }

            descend(e, agent);
        }
    }
}
运行驱动程序的
main
方法输出以下内容:

Agent[0] = UtilityCompany
Agent[1] = LargeCustomer

electricityPlan[0] = PlanUtility
electricityPlan[1] = LargecPlan

role[0] = Seller
role[1] = Buyer
Agent
  AuctionType: 
    AgentType: UtilityCompany
     RoleType: Seller
     PlanType: PlanUtility
    OrderType: SalesOrder
Agent
  AuctionType: 
    AgentType: LargeCustomer
     RoleType: Buyer
     PlanType: LargecPlan
    OrderType: PurchaseOrder


当然,上面的代码只是一个例子。
代理
类不一定需要所有这些访问器和变异器,或者根本不需要,它的成员都可以是公共的或受保护的。关键是你可以有一个代理列表,每个代理对象包含每种类型的成员,而不是一个带有ea的每种类型的列表ch index表示不同的代理。

您可能需要使用一些xml解析器库。Dom解析器、SAX解析器、Stax解析器就是其中的一些。是的,我知道,问题是如何获取元素,首先,我在解析xml文件:……Dom=db.parse(“file.xml”)..;后来我在解析文档,但使用的是:NodeList nl=docEle.getElementsByTagName(“代理”);你用什么来解析XML?我会用你正在使用的任何东西来写一个答案。我不明白这有什么困难。为什么你不能遍历dom并在深入分析时记住父元素?当你找到一个数组时,你会将保存的父元素添加到arrayList…?@Calicoder对我来说困难的部分是获得拍卖和PlanUtil谢谢