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

SonarQube does not show imported rules in quality profile
XML schema validation 'Security' issue
Printing content of XML in Twig
Oracle DB, validate xml during insert
Xpath getting sum of all children and grandchildren values
How to invoke a bash script from xml file
AS3 decoding XML file
Is there any way to make a tag in XSLT as optional?
xslt transform with escape entity
How to convert XML characters to utf8?
Trimming specific characters from an XML node value in XSL?
Combining several XPaths into a single XPath
How to return data XML schema defination in WCF?
Shell | removing repetitive lines
Is it wrong in XML to have element nodes as siblings of text nodes?
XPath predicate using last function

Categories

HOME
porting
spark-streaming
c99
redux-form
saml-2.0
apiblueprint
pclxl
can
cublas
alsa
pyqt4
missing-data
gluon-mobile
frontend
webix
performancepoint
qpython
octave
openpyxl
why3
mxgraph
emoji
zerobrane
symmetricds
3nf
heat
scsi
fileserver
boost-icl
windows-xp
simpleitk
react-toolbox
scriptella
interpreter
draft-js-plugins
dapper-extensions
xcode-ui-testing
moses
amazon-quicksight
has-and-belongs-to-many
linked-data
userdefaults
mobx
spring-security4
nested-lists
salesforce-communities
openalpr
xdocreport
apns-php
demo
mcustomscrollbar
comparison-operators
dbnull
proget
yii2-api
tinymce-3
insight
bluez
x-ray
quicktime
flac
jtree
usart
atlas
myspace
iotivity
flex4.6
uicolor
x-tag
refinerycms
jtwig
atan2
dynatree
rubaxa-sortable
haskell-warp
graphics2d
rapidsvn
execve
spy++
machine-instruction
paw
tweenlite
insight.database
jjaql
winginx
jquery-slider
paste
drupal-nodes
isqlquery
tlf
facebook-timeline
sentestingkit
vfs
wcf-configuration
apache-commons-dbutils
u2netdk
uipagecontrol
mtu
timertask
object-database
easyb
zend-rest
scrollbars
dsl-tools
windows-identity

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