to_element: add trait to convert a Node to a Element

This commit is contained in:
Matt Bilker
2018-09-15 05:17:08 +00:00
parent 8810290baf
commit dff69fe00e
2 changed files with 51 additions and 0 deletions

View File

@@ -28,6 +28,7 @@ mod options;
mod printer;
mod reader;
mod sixbit;
mod to_element;
mod value;
mod writer;
@@ -47,6 +48,7 @@ pub use node::{ExtraNodes, Node, NodeCollection};
pub use options::Options;
pub use de::from_bytes;
pub use ser::to_bytes;
pub use to_element::ToElement;
pub use value::Value;
pub use writer::{Writer, Writeable};

49
src/to_element.rs Normal file
View File

@@ -0,0 +1,49 @@
use minidom::Element;
use node::Node;
use value::Value;
pub trait ToElement {
fn to_element(&self) -> Element;
}
impl ToElement for Node {
fn to_element(&self) -> Element {
let mut elem = Element::bare(self.key());
if let Some(value) = self.value() {
elem.set_attr("__type", value.standard_type().name);
match value {
Value::String(value) => {
elem.append_text_node(value.as_str());
},
Value::Array(_, values) => {
elem.set_attr("__count", values.len());
let value = Value::array_as_string(values);
elem.append_text_node(value);
},
value => {
let value = value.to_string();
elem.append_text_node(value);
},
}
}
if let Some(attributes) = self.attributes() {
for (key, value) in attributes {
elem.set_attr(key.as_str(), value.as_str());
}
}
if let Some(children) = self.children() {
for child in children {
let child = child.to_element();
elem.append_child(child);
}
}
elem
}
}