#xml #xpath #dom #node #tree

etree

支持XPath的XML DOM库

8个版本

0.3.2 2022年11月25日
0.3.1 2022年10月27日
0.2.2 2022年6月7日
0.2.1 2022年5月21日
0.1.0 2022年3月18日

#13 in #xpath

每月 50 次下载

MIT/Apache

78KB
1.5K SLoC

Rust-Etree

Rust-Etree on Travis CI

支持XPath的XML DOM库。

用法

将以下内容放入您的 Cargo.toml

[dependencies]
etree = "0.1"
use etree::*;
use std::path::Path;

fn create_xml<P:AsRef<Path>>(path:P) {
    let mut tree:ETree = ETree::from(ETreeNode::new("ROOT"));
    tree.set_encoding("UTF-8");
    tree.set_standalone("no");
    let root_pos = tree.root();

    // append first child
    let mut child1:ETreeNode = ETreeNode::new("CHILD-A");
    child1.set_attr("DEST", "CHN");
    let child1_pos = tree.append_child_node(root_pos, child1).unwrap();
    // append another child after first child
    let mut child2:ETreeNode = ETreeNode::new("CHILD-B");
    child2.set_text("Shanghail");
    tree.append_next_node(child1_pos, child2);
    // append another child before first child
    let mut child3:ETreeNode = ETreeNode::new("CHILD-C");
    child3.set_attr("DEST", "CHN");
    child3.set_text("Shanghail");
    tree.append_previous_node(child1_pos, child3);
    // append a child in the first child
    let mut child4:ETreeNode = ETreeNode::new("SUBCHILD-A");
    child4.set_text("EAST");
    let pos = tree.find("//CHILD-A").unwrap(); // after inserting child3, child1_pos becomes invaild
    tree.append_child_node(pos, child4);
    tree.pretty("\n  ");
    tree.write_file(path).ok();
}

fn modify_xml<P:AsRef<Path>>(path_in:P, path_out:P) {
    let mut tree = ETree::parse_file(path_in);
    let subtree_pos = tree.find("//CHILD-A").unwrap();
    let mut subtree = tree.subtree(subtree_pos);
    let subtree_child_pos = subtree.find("/SUBCHILD-A").unwrap();
    if let Some(node) = subtree.node_mut(subtree_child_pos) {
        node.set_text("WEST");
    }
    // tree.append_next_tree(subtree_pos, subtree.clone());
    let parent_pos = tree.parent(subtree_pos).unwrap();
    tree.append_child_tree(parent_pos, subtree);
    tree.write_file(path_out).ok();
}

许可协议

根据您的选择,在Apache许可证,版本2.0MIT许可证下授权。
除非您明确声明,否则根据Apache-2.0许可证定义的,您有意提交以包含在此包中的任何贡献,应如上双重许可,不附加任何额外条款或条件。

依赖项

~4.5–6MB
~110K SLoC