473,396 Members | 1,785 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

simple XML question

i know it's quite simple, but i looked around for hours and i dont seem to be able to get it, excuse my nubiness pleaseeee

i need to parse an xml document, to take out the values inside since i'm using it as a database,

here's a sample xml file

<?xml version="1.0" ?><amman Address="3rd area" Hazard="weapons" Name="third" Owner="tarik" Phone="6453222" PhotoAddress="C:\Users\tarik\Desktop\DSC_0018.jpg" PrevUsed="project1" />

i need to extract the values just as a string, so if i ask for address ill just get 3rd area

supposing the XML file is located at c:/tempDB

eternally grateful for an answer!!

T
Sep 14 '09 #1
6 2220
I'm not familiar with XML myself but I think this should get you started.

Using xml.dom.minidom (http://docs.python.org/library/xml.dom.minidom.html) you can parse a file which should return a Document object which is documented here. You can then (I believe) use the Document methods to grab elements and values and the like.

Hope this helps!
Sep 14 '09 #2
bvdet
2,851 Expert Mod 2GB
I have done some XML parsing, and it was not simple to me! The following will parse the document into a dictionary:
Expand|Select|Wrap|Line Numbers
  1. from xml.dom.minidom import parseString
  2.  
  3. xmlStr = '''<?xml version="1.0" ?>
  4.     <amman Address="3rd area"
  5.            Hazard="weapons"
  6.            Name="third"
  7.            Owner="tarik"
  8.            Phone="6453222"
  9.            PhotoAddress="C:\Users\tarik\Desktop\DSC_0018.jpg"
  10.            PrevUsed="project1" />'''
  11.  
  12. xmlDoc = parseString(xmlStr)
  13.  
  14. def getNodeDict(doc, dd={}):
  15.     '''Return a dictionary of node names and attribute names and values
  16.     found in an XML document parseString instance. The keys are the node
  17.     names and each value is a list of dictionaries (a list is used since an
  18.     XML document can have multiple nodes with the same name). The keys of
  19.     each dictionary in the list are the attribute names and the values are
  20.     the attribute values. All keys and values are converted to regular
  21.     strings.'''
  22.     if doc == None: return None
  23.     for child in doc.childNodes:
  24.         # Skip all nodes except ELEMENT_NODE
  25.         if child.nodeType == 1:
  26.             # dict of attribute/values
  27.             s = child.attributes
  28.             if s:
  29.                 dd.setdefault(str(child.nodeName),
  30.                               []).append(dict(zip([str(item) for item in s.keys()],
  31.                                                    [str(item.value) for item in s.values()])))
  32.             if child.hasChildNodes():
  33.                 dd = self.getNodeDict(child, dd)
  34.     return dd
  35.  
  36. print
  37.  
  38. for key, value in getNodeDict(xmlDoc).items():
  39.     print "Node Name: %s" % (key)
  40.     print "Attributes:"
  41.     for item in value:
  42.         for x in item:
  43.             print '    %s: %s' % (x, item[x])
Output:
Expand|Select|Wrap|Line Numbers
  1. >>> 
  2. Node Name: amman
  3. Attributes:
  4.     PrevUsed: project1
  5.     Name: third
  6.     Hazard: weapons
  7.     PhotoAddress: C:\Users arik\Desktop\DSC_0018.jpg
  8.     Phone: 6453222
  9.     Address: 3rd area
  10.     Owner: tarik
  11. >>>
This code has not been tested on anything other than your document.
Sep 15 '09 #3
i cant thank you enough!!! i bow before you master,

i shall try the code tomorrow i hope cause it's darn late here,

thanks again

T
Sep 15 '09 #4
couldnt sleep without trying it!

first of all, it works perfectly, i dont know how to thank you,

but the boring part is, can i ask a couple of questions concerning?

if child.nodeType == 1: # very clear, but how do i get a reference of what this might return? i've read XML documents and ive read MINIDOM documents, but the gap in between of what to use where, how do you recommend i understand that?


dd.setdefault(str(child.nodeName),[]).append(dict(zip([str(item) for item in s.keys()],
[str(item.value) for item in s.values()])))
#i get how it's working, but this is an out of place question, how do i understand functions like "setdefault" and "zip" ? i mean the documantation can only get u this much, then it ends up losing u! i recently moved from Autodesk|Maya's python, and working on programming more OS stuff,

thank you so much for your help!

T
Sep 15 '09 #5
bvdet
2,851 Expert Mod 2GB
To begin with, I like this website for learning the basics of XML.

There are several types of nodes, one type being ELEMENT_NODE.
Expand|Select|Wrap|Line Numbers
  1. >>> xmlDoc.ELEMENT_NODE
  2. 1
  3. >>> xmlDoc.firstChild.nodeType
  4. 1
To see a list of the available attributes of an XML document parseString instance:
Expand|Select|Wrap|Line Numbers
  1. >>> for item in dir(xmlDoc):
  2. ...     print item
  3. ...     
  4. ATTRIBUTE_NODE
  5. CDATA_SECTION_NODE
  6. COMMENT_NODE
  7. DOCUMENT_FRAGMENT_NODE
  8. DOCUMENT_NODE................................
Built-in function dict() returns a dictionary. Built-in function zip() returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences. Example:
Expand|Select|Wrap|Line Numbers
  1. >>> s1 = [1,2,3]
  2. >>> s2 = ['a','b','c']
  3. >>> zip(s1, s2)
  4. [(1, 'a'), (2, 'b'), (3, 'c')]
  5. >>> dict(zip(s1,s2))
  6. {1: 'a', 2: 'b', 3: 'c'}
  7. >>> 
Dictionary method setdefault(key[, x]) returns the value of the dictionary key if the key exists, otherwise returns x and sets the dictionary key to x. Example:
Expand|Select|Wrap|Line Numbers
  1. >>> dd = dict(zip(s1,s2))
  2. >>> dd.setdefault(3, [])
  3. 'c'
  4. >>> dd.setdefault(4, [])
  5. []
  6. >>> dd
  7. {1: 'a', 2: 'b', 3: 'c', 4: []}
  8. >>> dd.setdefault(4, []).append('d')
  9. >>> dd
  10. {1: 'a', 2: 'b', 3: 'c', 4: ['d']}
  11. >>> 
Sep 15 '09 #6
could not have been clearer! thank you master

cheers

T
Sep 16 '09 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Patchwork | last post by:
Hi Everyone, Please take a look at the following (simple and fun) program: //////////////////////////////////////////////////////////////////////////// ///////////// // Monster Munch, example...
1
by: Proteus | last post by:
Any help appreciated on a small perl project I need to write for educator/teaching purposes. I have not programmed perl for some time, need to get up to speed, maybe some kind souls hrere will help...
2
by: Raskolnikow | last post by:
Hi! I have a very simple problem with itoa() or the localtime(...). Sorry, if it is too simple, I don't have a proper example. Please have a look at the comments. struct tm *systime; time_t...
3
by: Peter | last post by:
Hello Thanks for reviewing my question. I would like to know how can I programmatically select a node Thanks in Advanc Peter
7
by: abcd | last post by:
I am trying to set up client machine and investigatging which .net components are missing to run aspx page. I have a simple aspx page which just has "hello world" printed.... When I request...
4
by: dba_222 | last post by:
Dear Experts, Ok, I hate to ask such a seemingly dumb question, but I've already spent far too much time on this. More that I would care to admit. In Sql server, how do I simply change a...
14
by: Giancarlo Berenz | last post by:
Hi: Recently i write this code: class Simple { private: int value; public: int GiveMeARandom(void);
30
by: galiorenye | last post by:
Hi, Given this code: A** ppA = new A*; A *pA = NULL; for(int i = 0; i < 10; ++i) { pA = ppA; //do something with pA
10
by: Phillip Taylor | last post by:
Hi guys, I'm looking to develop a simple web service in VB.NET but I'm having some trivial issues. In Visual Studio I create a web services project and change the asmx.vb file to this: Imports...
17
by: Chris M. Thomasson | last post by:
I use the following technique in all of my C++ projects; here is the example code with error checking omitted for brevity: _________________________________________________________________ /*...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.