xml


How to capture some values using xml-rs (if it's possible)


I'm using xml-rs 0.4 and I need to capture several fields and values:
name
"visible"
True
From this sample XML file:
<?xml version="1.0" encoding="UTF-8"?>
<interface>
<requires lib="rsTest+" version="1.00"/>
<object class="rsTestWindow" id="window1">
<property name="can_focus">False</property>
</object>
</interface>
After looking at the xml-rs code in Github, I was able to capture name and "visible":
for att in attributes {
// test
let temp_name_local_name = att.name.local_name.clone();
let temp_value= att.value.clone();
println!("{}+{}+{}", temp_name_local_name, temp_value);
}
Stdout:
name+visible
I could not figure out how to capture True.
This is my complete code:
extern crate xml;
use std::fs::File;
use std::io::BufReader;
use xml::reader::{EventReader, XmlEvent};
use xml::name::{Name, OwnedName};
fn indent(size: usize) -> String {
const INDENT: &'static str = " ";
(0..size)
.map(|_| INDENT)
.fold(String::with_capacity(size * INDENT.len()), |r, s| r + s)
}
fn main() {
let file = File::open("./src/sample.xml").unwrap();
let file = BufReader::new(file);
let parser = EventReader::new(file);
let mut depth = 0;
for e in parser {
match e {
Ok(XmlEvent::StartElement {
name,
attributes,
namespace,
}) => {
/* //test
let n: xml::namespace::Namespace = namespace;
if n.is_empty() {
println!("empty");
}else{
println!("no empty");
}
*/
let t: String = name.local_name;
println!("{}", t);
if name.prefix.is_some() == true {
println!("{}", name.prefix.clone().unwrap().clone());
}
if name.namespace.is_some() == true {
println!("{}", name.namespace.unwrap().clone());
}
if attributes.is_empty() == true {
//"test".to_string()
} else {
for att in attributes {
//let tet: xml::name::OwnedName = att.name;
let temp_name_local_name = att.name.local_name.clone();
let temp_value = att.value.clone();
println!("{}+{}", temp_name_local_name, temp_value);
/* //test
if att.name.namespace.is_some() == true {
println!("{}", att.name.namespace.unwrap().clone());
}
if att.name.prefix.is_some() == true {
println!("{}", att.name.prefix.unwrap().clone());
}
*/
}
}
depth += 1;
}
Ok(XmlEvent::ProcessingInstruction { name, data }) => {
/* //test
if data.is_some() == true {
println!("{}", data.unwrap().clone());
}
println!("{}", name );
*/
}
Ok(XmlEvent::EndElement { name }) => {
//println!("{}-{}", indent(depth), name);
}
Err(e) => {
//println!("Error: {}", e);
break;
}
_ => {}
}
}
}
And my dependencies in Cargo.toml:
[dependencies]
xml-rs = "0.4"
As xml-rs is a pull parser, each structural part of an XML element is captured by multiple events, in this case of type XmlEvent. Namely, XmlEvent::StartElement is triggered after parsing an opening (or bodiless) XML tag, and provides the element's name, namespace and list of attributes.
On the other hand, XmlEvent::Characters captures text between XML tags. This is the event that is missing in your pattern matching.
In your case, this means that you must keep track of the last entered element in order to assign that text to the entry. One possible solution is to keep a mutable record and use it at the end of an element, where it will be complete.
let mut record = MyStruct { /* ... */ };
for e in parser {
match e {
Ok(XmlEvent::StartElement { name, attributes, namespace }) => {
record.name = name;
// ...
}
Ok(XmlEvent::Characters(text) => {
record.value = text; // or something else
}
Ok(XmlEvent::EndElement { .. }) => {
// record is finished, use it or save it here
// ...
}
// ...
}
}
Ideally, you could build your own iterator type that abstracts XMLEvent away, and provides iteration over complete records. Here's an example from one of my projects.

Related Links

Can I add my own tags in a rss item?
Move sub nodes into parent attributes with XSLT
Is there a way to ignore namespaces during an XSL transformation?
How do I import XML external entities that contain elements with custom namespaces?
XSD Visualization?
Defining pattern of text() node of complex mixed element
How can I remove a namespace from an XML document?
How do I view RSS feeds as formatted XML?
XPath to find nested values
Is there a way to map a tag in flex to components in multiple directories?
How to implement a sharepoint lists webservice
EXI (efficient XML interchange) coming… Are XML APIs ready?
Parsing XML with AS3
How to use Xpath in Yahoo! Widgets to traverse a tree?
X509Certificate2 validation on web service
Deleting XML elements in WiX

Categories

HOME
android
xml
turing-machines
gpu
jax-rs
youtube-data-api-v3
devise
error-handling
grafana
tivoli
carousel
mips
visual-studio-emulator
babeljs
vsm
iis-6
project
enthought
gkturnbasedmatch
renjin
cumulocity
bitnami
package-managers
coin3d
internationalization
google-content-api
pyramid
sencha-touch
topology
ember-cli
qliksense
jquery-callback
dapper-extensions
beautifier
angularjs-components
asymptotic-complexity
handler
spotipy
iis-express
panoramas
recurring-events
scatter3d
memory-address
twos-complement
vue-chartjs
video-capture
xajax
cd
projects-and-solutions
password-protection
metawidget
spring-mvc-test
tasm
trigonometry
facebook-social-plugins
nanoc
fclose
dtsearch
azure-cli
java-bytecode-asm
webjars
preprocessor
model-associations
drawstring
udpclient
gcloud-ruby
upx
ellucian-scribe
jnlua
linklabel
avisynth
ons-api
fuelcms
toolkit
rpart
atoi
sha512
aspectj-maven-plugin
user-permissions
gamekit
showdialog
post-commit-hook
psr-4
angular-carousel
template-deduction
parallel-testing
reflector
ios8-extension
kendo-dataviz
code-duplication
dtmf
android-icons
apache-abdera
extreme-programming
correlated-subquery
agility.js
gobject-introspection
timthumb
socketserver
nhprof
load-time
vs-android
object-database
sifr
lalr
cldc
dojo-dnd
soappy

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App