保存和加载XML文件的步骤是什么?

what is the step to save to and load xml file?

提问人:user22896733 提问时间:11/15/2023 最后编辑:user22896733 更新时间:11/15/2023 访问量:50

问:

保存到和加载 XML 文件的步骤是什么?保存到和加载 XML 文件的步骤是什么?

    if (element.getElementsByTagName(Customer.KEY_NAME).getLength() > 0) {
        name = element.getElementsByTagName(Customer.KEY_NAME).item(0).getTextContent();
    }

我有一个关于此代码中的 item(0) 部分的问题。为什么它被用作 item(0) 而不是 item(i)?我不确定为什么代码只获取第一个元素而不是遍历多个元素。您能解释一下在这里使用 item(0) 的目的以及为什么它不是 item(i) 吗?

在此处输入图像描述 在此处输入图像描述

Java XML binary-search-tree

评论

0赞 VGR 11/15/2023
您需要编辑您的问题并提供有关任务的更多详细信息。为什么代码需要遍历多个元素?你的程序想做什么?
0赞 jdweng 11/15/2023
getElementsByTagName 正在获取节点以及节点的所有后代。索引 0 只是获取没有后代的父项。

答:

0赞 queeg 11/15/2023 #1

您的代码可能将某些输入文档解析为 DOM 结构。 然后,它尝试使用元素 customer。KEY_NAME(我们不知道标签名称,因为它存储在常量中)。

首先检查该元素是否包含在 DOM 中:返回具有该名称的所有元素的列表。您可能只期望一个这样的元素 - 但 XML 本身也允许没有或多个元素。如果该列表包含条目,则需要检索该值。element.getElementsByTagName(Customer.KEY_NAME)

因此,再次调用返回列表的方法,并且由于我们期望该列表中只有一个条目,因此处理第一个条目就足够了。第一个是用 检索的。element.getElementsByTagName(Customer.KEY_NAME).item(0)

现在你有了KEY_NAME元素,但你需要有文本内容 - 因此调用了 .getTextContent() 方法,结果存储在变量中。name

回到你的问题:你会写一些东西,就像你试图遍历KEY_NAME元素列表一样。如果您的文档结构可能包含评估所需的多个此类元素,这确实是更好的解决方案。这就是我相信您的文档将只包含一个这样的值的地方。item(i)

因此,事实是:您的输入文档是什么性质,您希望如何评估它?

0赞 user22896733 11/15/2023 #2

xml-保存

public void save(String tableName, 列出客户) {

    File f = new File(FileUtil.getTableFileName(tableName));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        // make the xml tree
        // use factory to get the instance of document builder
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.newDocument();
        // Root element <customers>
        Element rootElem = doc.createElement(Customer.KEY_ROOT);
        doc.appendChild(rootElem);

        for (Customer customer : customers) {
            Element customerElem = doc.createElement(Customer.KEY_ELEMENT);
            rootElem.appendChild(customerElem);

            // child element <ID> under <customer>
            Element cid = doc.createElement(Customer.KEY_ID);
            cid.appendChild(doc.createTextNode(Integer.toString(customer.getId())));
            customerElem.appendChild(cid);

            if (customer.getName() != null) {
                Element name = doc.createElement(Customer.KEY_NAME);
                name.appendChild(doc.createTextNode(customer.getName()));
                customerElem.appendChild(name);
            }

            if (customer.getAddress() != null) {
                Element address = doc.createElement(Customer.KEY_ADDRESS);
                address.appendChild(doc.createTextNode(customer.getAddress()));
                customerElem.appendChild(address);
            }

            if (customer.getCity() != null) {
                Element city = doc.createElement(Customer.KEY_CITY);
                city.appendChild(doc.createTextNode(customer.getCity()));
                customerElem.appendChild(city);
            }

            if (customer.getPostCode() != null) {
                Element postCode = doc.createElement(Customer.KEY_POSTCODE);
                postCode.appendChild(doc.createTextNode(customer.getPostCode()));
                customerElem.appendChild(postCode);
            }

            if (customer.getCountry() != null) {
                Element country = doc.createElement(Customer.KEY_COUNTRY);
                country.appendChild(doc.createTextNode(customer.getCountry()));
                customerElem.appendChild(country);
            }
        }
        // save the xml file
        // Transformer is for process XML from a variety of sources and write the
        // transformation
        // output to a variety of sinks
        Transformer transformer = TransformerFactory.newInstance().newTransformer();

        // set xml encoding to utf-8
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        // pretty print
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(f);
        transformer.transform(source, result);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

XML 加载 public List load(String tableName) {

    List<Customer> customers = new ArrayList<>();

    File f = new File(FileUtil.getTableFileName(tableName));
    if (!f.exists()) {
        return customers;
    }

    // TODO: Complete this method
    // START YOUR CODE
    try {
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(f);
        doc.getDocumentElement().normalize();

        NodeList nodeList = doc.getElementsByTagName(Customer.KEY_ELEMENT);

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);

            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;

                int id = Integer.parseInt(element.getElementsByTagName(Customer.KEY_ID).item(0).getTextContent());

                String name = null, address = null, city = null, postcode = null, country = null;

                if (element.getElementsByTagName(Customer.KEY_NAME).getLength() > 0)
                    name = element.getElementsByTagName(Customer.KEY_NAME).item(0).getTextContent();

                if (element.getElementsByTagName(Customer.KEY_ADDRESS).getLength() > 0)
                    address = element.getElementsByTagName(Customer.KEY_ADDRESS).item(0).getTextContent();

                if (element.getElementsByTagName(Customer.KEY_CITY).getLength() > 0)
                    city = element.getElementsByTagName(Customer.KEY_CITY).item(0).getTextContent();

                if (element.getElementsByTagName(Customer.KEY_POSTCODE).getLength() > 0)
                    postcode = element.getElementsByTagName(Customer.KEY_POSTCODE).item(0).getTextContent();

                if (element.getElementsByTagName(Customer.KEY_COUNTRY).getLength() > 0)
                    country = element.getElementsByTagName(Customer.KEY_COUNTRY).item(0).getTextContent();

                Customer customer = new Customer(id, name, address, city, postcode, country);
                customers.add(customer);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

预购 BST public class ParcelBST extends BinarySearchTree implements Iterable {

public ParcelBST(Parcel value, ParcelBST leftNode, ParcelBST rightNode) {
    super(value, leftNode, rightNode);
}

public ParcelBST(BinarySearchTree<Parcel> parcelBST) {
    //这里写了root是value
    super(parcelBST.value,parcelBST.leftNode,parcelBST.rightNode);
}

public ParcelBST(Tree<Parcel> parcelTree) {
    super(parcelTree.value,parcelTree.leftNode,parcelTree.rightNode);
}

public ParcelBST(Parcel value) {
    super(value);
}


@Override
public Iterator<Parcel> iterator() {
    return new IteratorPreOrder();
}

class IteratorPreOrder implements Iterator<Parcel> {
    // Hint: value, left/right sub-trees can be accessed by:
    //    ParcelBST.this.value    ParcelBST.this.leftNode   ParcelBST.this.rightNode
    // Or equivalently directly:
    //    value   leftNode    rightNode

    private Deque<BinarySearchTree<Parcel>> stack = new LinkedList<>();

    // You may add methods and variables here if you wish
    //这个方法是干什么?

    public IteratorPreOrder() {
        //初始preorder的迭代器
        // You may add code here if you wish
        //为什么要用外部类?
        //检查的有没有根节点,如果根节点

        if(ParcelBST.this.value != null){
            stack.push(ParcelBST.this);
        }
    }

    //在这个迭代器里,再去写方法

    @Override
    public boolean hasNext() {
        // TODO
        // START YOUR CODE
        //是用来判断stack里有没有东西的
        if(stack.isEmpty()){
            return false;
        }
        return true;
        // END YOUR CODE
    }

    @Override
    //这个方法是为了去迭代树
    public Parcel next() {
        // TODO
        // START YOUR CODE
        if (!hasNext()) {
            throw new NoSuchElementException();
        }

        BinarySearchTree<Parcel> current = stack.pop();

        //right
        if (current.rightNode != null && current.rightNode.value != null) {
            stack.push((BinarySearchTree<Parcel>) current.rightNode);
        }

        //left
        if (current.leftNode != null && current.leftNode.value != null) {
            stack.push((BinarySearchTree<Parcel>) current.leftNode);
        }
        // END YOUR CODE
        //返回整个curren的value
        return current.value;
    }
}

解析 器

public void parseExp() {

    // TODO: Complete this method
    // START YOUR CODE

    Token token1 = tokeniser.takeNext();
    Token token2 = tokeniser.takeNext();

    if (token1 == null || token2 == null)
        return; // If any token is null, return without parsing

    // Validate the brackets
    if (!token1.value.contains("(") || !token1.value.contains(")") || !token2.value.contains("(") || !token2.value.contains(")"))
        return; // Return if brackets are missing in any token

    // Extract and validate column names
    String columnsStr = token1.value.substring(token1.value.indexOf("(") + 1, token1.value.indexOf(")")).trim();
    String[] columns = columnsStr.split(",");
    List<String> validColumns = Arrays.asList(Customer.KEY_ID, Customer.KEY_NAME, Customer.KEY_ADDRESS, Customer.KEY_CITY,
            Customer.KEY_POSTCODE, Customer.KEY_COUNTRY);
    for (String column : columns) {
        if (!validColumns.contains(column.trim())) {
            return; // Return if any column name is invalid
        }
    }

    // Extract and validate values
    String valuesStr = token2.value.substring(token2.value.indexOf("(") + 1, token2.value.indexOf(")")).trim();
    String[] values = valuesStr.split(",");

    // Assuming values should match the columns
    if (columns.length != values.length)
        return; // Return if columns and values count do not match

    // Execute the SQL command (Inserting into XMLTable in this case)
    Customer customer = new Customer();
    // Assuming the order of columns matches the order in the Customer class
    customer.setId(Integer.parseInt(values[0].trim()));
    customer.setName(values[1].trim().replace("'", ""));
    customer.setAddress(values[2].trim().replace("'", ""));
    customer.setCity(values[3].trim().replace("'", ""));
    customer.setPostCode(values[4].trim().replace("'", ""));
    customer.setCountry(values[5].trim().replace("'", ""));

    table.insert(Customer.TABLE_NAME, customer); // Inserting the customer into the XMLTable

    // END YOUR CODE
}

}

分词器

公共无效 next() { 缓冲区 = buffer.trim();删除空格

    if(buffer.isEmpty()) {
        currentToken = null;    // if there's no string left, set currentToken null and return
        return;
    }

    // ########## YOUR CODE STARTS HERE ##########
    String regex = "([A-Za-z]+)|([0-9]+)|([^A-Za-z0-9])";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(buffer);

    if(matcher.find()){
        String matechedSubString = matcher.group();

        if(Character.isLowerCase(matechedSubString.charAt(0))){
            if(containUpperCase(matechedSubString)){
                if(matechedSubString.length() <=3){
                    currentToken = new Token(matechedSubString, Token.Type.SHORT_CAMEL_CASE_WORD);
                }else {
                    currentToken = new Token(matechedSubString, Token.Type.LONG_CAMEL_CASE_WORD);
                }
            }else {
                currentToken = new Token(matechedSubString, Token.Type.LOWER_CASE_WORD);
            }
        } else if (Character.isUpperCase(matechedSubString.charAt(0))) {
            if (containLowerCase(matechedSubString)) {
                if (matechedSubString.length() <= 3) {
                    currentToken = new Token(matechedSubString, Token.Type.SHORT_CAMEL_CASE_WORD);
                } else {
                    currentToken = new Token(matechedSubString, Token.Type.LONG_CAMEL_CASE_WORD);
                }
            } else {
                currentToken = new Token(matechedSubString, Token.Type.UPPER_CASE_WORD);
            }
        } else if (Character.isDigit(matechedSubString.charAt(0))) {
            currentToken = new Token(matechedSubString, Token.Type.INTEGER_NUMBER);
        }else {
            currentToken = new Token(matechedSubString, Token.Type.NON_ALPHANUMERIC);
        }
    }

    // ########## YOUR CODE ENDS HERE ##########

    // Remove the extracted token from buffer
    int tokenLen = currentToken.getValue().length();
    buffer = buffer.substring(tokenLen);
}

评论

0赞 Community 11/16/2023
您的答案可以通过额外的支持信息得到改进。请编辑以添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到有关如何写出好答案的更多信息。