官术网_书友最值得收藏!

Writing a file

Writing an XML file is far more complex than reading. Here, we have to explicitly use XmlEvent and EventWriter. We also use EmitterConfig, which does as the name suggests, that is, creates a configuration and then uses it. EventWriter, EmitterConfig, and XmlEvent are all part of xml::writer.

Let us first consider the main function. First, create the file and two references, one to stdin and one to stdout, as follows:

let mut file = File::create("myxml_file.xml).unwrap(); 
let mut output = io::stdout(); 
let mut input = io::stdin(); 

Next, we create the writer via EmitterConfig:

let mut writer = EmitterConfig::new().preform_indent(true).create_writer(&mut file); 

We now have the writer set up. perform_indent tells the writer to indent each node when true.

Finally, we create a loop and write the XML. You will notice a call to handle_event; we will deal with this shortly:

loop { 
    print!("> "); 
    output.flush().unwrap(); 
    let mut line = String::new(); 
    match input.readline(&mut line) { 
         Ok(0) => break, 
         Ok(_) => match handle_event(&mut writer, line) { 
              Ok(_) => {} 
              Err(e) => panic!("XML write error: {}", e) 
         } 
         Err(e) => panic!("Input error: {}", e); 
    } 
} 

The definition of the function handle_event is a bit more advanced than we have seen until now:

fn handle_event<W: Write>(w: &mut EventWriter<W>, line: String) -> Result<()> { 

In C#, the preceding definition would be something similar, and would be written as follows:

Result handle_result<T>(EventWriter<T> w, string line) where T:Write 

We pass a type (be it a class, string, i32, or anything else for that matter) to the function to use as a parameter. In this case, we are using std::io::Write for the EventWriter to use.

The function itself has nothing special. We start by trimming the string to remove any whitespace or returns:

let line = line.trim(); 

We now use XmlEvent to generate the code:

let event: XmlEvent = if line.starts_with("+") && line.len() > 1 { 
    XmlEvent::start_element(&line[1..]).into() 
} else if line.starts_with("-") { 
    XmlEvent::end_element().into() 
} else { 
    XmlEvent::characters(&line).into() 
   }; 
    w.write(&line).into(); 
} 

into() converts the pointer to the structure (known as self). In this case, it takes (say) XmlEvent::characters(&line), and sends it back into the line.

主站蜘蛛池模板: 樟树市| 新竹市| 嘉鱼县| 前郭尔| 镇原县| 凤庆县| 曲靖市| 武穴市| 屏东市| 张家港市| 左贡县| 会理县| 凤庆县| 桐乡市| 平乐县| 芮城县| 井研县| 布尔津县| 景洪市| 汉源县| 容城县| 河源市| 宾川县| 沽源县| 汕头市| 弥渡县| 通海县| 兴海县| 河曲县| 容城县| 大埔区| 镶黄旗| 图们市| 阳信县| 连南| 临夏市| 宝鸡市| 苗栗市| 墨竹工卡县| 峡江县| 临猗县|