What Do I Need to Do to Get Hash.From_Xml() to Work

What do I need to do to get Hash.from_xml() to work?

Just require 'active_support' doesn't do very much, you have to pull in the pieces sort of by hand. If you want all of ActiveSupport:

require 'active_support/all'

or if you just want the Hash extensions:

require 'active_support/core_ext/hash'

Rails Hash.from_xml not giving expected results

Thanks for adding the additional information that this is a rating for an interviewee. Using this domain information in your code will likely improve it. You haven't posted any code, but generally using domain objects leads to more concise and more readable code.
I recommend creating a simple class representing a Rating, rather than transforming data from XML to a data structure.

class Rating
attr_accessor :image_filename, :criterion_1, :withdrew
end

Using the above class, here's one way to extract the fields from the XML using Nokogiri.

doc = Nokogiri::XML(xml)
ratings = []

doc.xpath('//Record').each do |record|
rating = Rating.new
rating.image_filename = record.at('Field[@id="ImageFilename"]/Value/text()').to_s
rating.criterion_1 = record.at('Field[@id="Criterion_1"]/Value/text()').to_s
rating.withdrew = record.at('Field[@id="Withdrew"]/Value/text()').to_s
ratings << rating
end

Now, ratings is a list of Rating objects, each with methods to retrieve the data. This is a lot cleaner than delving into a deep data structure. You could even improve on the Rating class further, for example creating a withdrew? method that returns a true or false.

converting from xml name-values into simple hash

There are a few libraries you can use in Ruby to do this.

Ruby toolbox has some good coverage of a few of them:

https://www.ruby-toolbox.com/categories/xml_mapping

I use XMLSimple, just require the gem then load in your xml file using xml_in:

require 'xmlsimple'
hash = XmlSimple.xml_in('session.xml')

If you're in a Rails environment, you can just use Active Support:

require 'active_support' 
session = Hash.from_xml('session.xml')

How to read values from xml and store it in hash map in java

You should check this for reading specific parameters from xml file:
this

But there is a better way for handling xml files. Since you didn't provide any more details, I'm going to post one way of reading data from xml file.

Easiest way is to define a type that represents data that is in your xml file. Then you can easily read and write that data into the xml file.

For example you define type Person:

public class Person{
private String username="";
private String password="";
private String address="";

// Constructor(s), getters, setters...
}

And when you want to save data into the xml, just serialize Person object:

public boolean serialize(Person p, String path) {
try {
XMLEncoder encoder = new XMLEncoder(new FileOutputStream(new File(path+File.separator+p.getUsername()+".xml")));
encoder.writeObject(s);
encoder.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

Now when you want to read from xml file, just deserialize it into Person object:

public Person deserialization(String name, String path) {
Person p=null;
try {
XMLDecoder decoder = new XMLDecoder(new FileInputStream(new File(path+File.separator+name+".xml")));
p=(Person) decoder.readObject();
decoder.close();
} catch (Exception e) {
e.printStackTrace();
}
return p;
}

And finally you can store it easier in HashMap:

HashMap<String, String> hash_map = new HashMap<String, String>();
hash_map.put(p.getUsername(),p.getPassword()); // p is a Person object

NOTE: This is just one way of doing it, you can adjust it to your needs. You should take care of the file path that you provide (if you use xml files from some server maybe approach is different, this example reffers to using xml files from local file system).
Also note that passwords should be protected, encrypted for example.

Parsing XML to a hash table

As others have stated minidom is the way to go here. You open (and parse) the file, while going through the nodes you check if its relevant and should be read. That way, you also know if you want to read the child nodes.

Threw together this, seems to do what you want. Some of the values are read by attribute position rather than attribute name. And theres no error handling. And the print () at the end means its Python 3.x.

I'll leave it as an exercise to improve upon that, just wanted to post a snippet to get you started.

Happy hacking! :)

xml.txt

<doc>
<id name="X">
<type name="A">
<min val="100" id="80"/>
<max val="200" id="90"/>
</type>
<type name="B">
<min val="100" id="20"/>
<max val="20" id="90"/>
</type>
</id>
</doc>

parsexml.py

from xml.dom import minidom
data={}
doc=minidom.parse("xml.txt")
for n in doc.childNodes[0].childNodes:
if n.localName=="id":
id_name = n.attributes.item(0).nodeValue
data[id_name] = {}
for j in n.childNodes:
if j.localName=="type":
type_name = j.attributes.item(0).nodeValue
data[id_name][type_name] = [(),()]
for k in j.childNodes:
if k.localName=="min":
data[id_name][type_name][0] = \
(k.attributes.item(1).nodeValue, \
k.attributes.item(0).nodeValue)
if k.localName=="max":
data[id_name][type_name][1] = \
(k.attributes.item(1).nodeValue, \
k.attributes.item(0).nodeValue)
print (data)

Output:

{'X': {'A': [('100', '80'), ('200', '90')], 'B': [('100', '20'), ('20', '90')]}}

Using Hash::extract() on Array from Xml

It isn't crystal clear from your question, but I assume this array

array(
'items' => array(
'item' => array(
(int) 0 => array(
'@item' => '3-394-001068-00000'),
(int) 1 => array(
'@item' => '3-394-001069-00000'),

is the result of your debug($xmlarray);, so we can rule out misslocation of a file (if I'm assuming wrong, do tell).

So, the hash is your problem.

See, according to docs, the {n} refers to "a numeric key", and "items" is clearly not. If you want to extract all "item" inside "items", it should be

Hash::extract($xmlarray, 'items.item');

and that will give you

array((int) 0 => array(
'@item' => '3-394-001068-00000'),
(int) 1 => array(
'@item' => '3-394-001069-00000'),
/*etc*/

and, if you want to have a much compact array (don't know if you need the index associations), you could try

Hash::extract($xmlarray, 'items.item.{n}.@item');

and that'll get you

array('3-394-001068-00000', '3-394-001069-00000')

perl: variable returns hash instead of string

A relevant snippet from my answer to Why is XML::Simple Discouraged?:

This means that you have to perform all kinds of checks to see what you actually got. But the sheer complexity of this encourages developers to make very bad assumptions instead.

It appears exactly that is happening here. That said, the data you want is accessible using the following:

 my $av_node = $attr->{'saml1:AttributeValue'};
$casAttrs{$name} = ref($av_node) ? $av_node->{content} : $av_node;

Note that still makes some of the aforementioned assumptions.

Get the sha1-hashed value from XML signature value

RSA signing is not actually the same as encrypting with the private key, but JCE promotes this mistake by allowing 'backwards' operations in Cipher for RSA (only) which actually do PKCS1-v1_5 signature and recovery instead of encryption and decryption as they were designed to.

For the original standardized RSA signature scheme in PKCS1 through v1.5, now retronymed RSASSA-PKCS1-v1_5, the value that is padded (with 'type' 01 multiple FFs and one 00) and modexp'ed with the private key is not just the hash but an ASN.1 structure containing the hash. See the encoding operation EMSA-PKCS1-v1_5 in section 9.2 of rfc8017 or rfc3447 or 9.2.1 in rfc2437, especially step 2 and (for the newer two versions) 'Notes' item 1.

Dupe Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

and Separate digest & signing using java security provider



Related Topics



Leave a reply



Submit