w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Setting an attribute value in XML file using ElementTree
Since the xml you've provided is not valid, here's an example: import xml.etree.ElementTree as ET xml = """<?xml version="1.0" encoding="UTF-8"?> <body> <approved-by approved="no"> <name>AB</name> <signature>errrrrn</signature> </approved-by> </body> """ tree = ET.fromstring(xml) sh = tree.find('approved-by') sh.set('approved', 'yes') print ET.tostring(tree) prints: <body> <approved-by approved="yes"> <name>AB</name> <signature>errrrrn</signature> </approved-by> </body> So, the first way you've tried works. Hope that helps.

Categories : Python

How to get ElementTree to output tabs etc in attribute values as numerical entities?
XML does not support most control characters, not even as entities. See the W3C Recommendation, and look for the Char production. You need to encode the information. Base64 encoding is the most usual.

Categories : Python

Python 2.5: ElementTree and UML in XML
register_namespace is only available since Python 2.7 There might be another way to preserve namespaces with ElementTree in 2.5, but I'm not aware of it. Alternatively, you could try another parsing library. lxml preserves namespaces and its API is compatible with ElementTree.

Categories : Python

Read GPX using Python ElementTree.register_namespace?
Why don't you just use an existing GPX library? shameless plug: With gpxpy https://github.com/tkrajina/gpxpy parsing waypoints from your file works perfectly: import gpxpy gpx_sample = """...your GPX sample here...""" gpx = gpxpy.parse(gpx_sample) for wpt in gpx.waypoints: print wpt.latitude, wpt.longitude Even if you don't want to use the library you can just check the code to see how it parses the XML file.

Categories : Python

Can findall or finditer be used in this python ElementTree example?
I recommend you to use lxml. You can use xpath expression with lxml. import lxml.etree root = lxml.etree.parse("example.xml") for instance in root.xpath('//Instance[descendant::UserValue[@title = "THIRD"][@value != ""]]'): print instance.get('name') If above code takes too much memory try following code: import lxml.etree class InstanceNamePrinter(object): def start(self, tag, attrib): if tag == 'Instance': self.name = attrib['name'] elif tag == 'UserValue': if attrib['title'] == 'THIRD' and attrib['value'] != '': print self.name def close(self): pass with open('example.xml') as xml: parser = lxml.etree.XMLParser(target=InstanceNamePrinter()) lxml.etree.parse(xml, parser)

Categories : Python

python ElementTree decoding error
If you do this: my_str = u'u2014' el.text = my_str.encode('UTF-8') you're setting the text to an utf-8 encoded version of the unicode character. It's the same as el.text = 'xe2x80x94' Now you don't have an unicode character anymore, but a series of bytes. If you then do: tostring(root, encoding='UTF-8') You're saying you want the content encoded as utf-8. To to that, internally the string has first to be decoded to unicode using the default encoding (ascii), and then encode as utf-8, which of course fails as the bytes in the string arn't in the ascii range. ElementTree is perfectly capable of working with unicode, so just give it unicode instead of str: >>> from xml.etree import ElementTree as et >>> e = et.Element('test') >>> e.text = u'u2014' >&

Categories : Python

Python extract nodes containing tag using ElementTree
What about this: import xml.etree.ElementTree as ET import sys name = str.strip(sys.argv[1]) filename = str.strip(sys.argv[2]) fp = open("sample.xml","r") tree = ET.parse(fp) root = tree.getroot() for offers in root.findall('.//{http://url}Offers'): value_found = False for amount in offers.findall('.//{http://url}Amount'): if amount.text == name: value_found = True break if value_found: print ET.tostring(offers) Prints <url:Offers xmlns:url="http://url"> <url:Offer> <url:OfferListing> <url:Price> <url:Amount>1853</url:Amount> </url:Price> </url:OfferListing> </url:Offer> </url:Offers> <url:Offers xmlns:url="http://url">

Categories : Python

How to get grandchild elements from Elementtree in python
The root element is iterable: >>> import xml.etree.ElementTree as ET >>> xml = "<root><a><b>....</b><c>....</c><d>....</d></a><d><c><a></a></c></d></root>" >>> root = ET.fromstring(xml) >>> root <Element 'root' at 0x7fa86a7ea610> >>> for child in root: ... print child ... <Element 'a' at 0x7fa86a7ea650> <Element 'd' at 0x7fa86a7ea810> Getting specific grandchild elements: >>> root = ET.fromstring(xml) >>> root.find("d").getchildren() [<Element 'c' at 0x7fce44939650>, <Element 'a' at 0x7fce44939690>] If you want the tag rather than the ElementTree object: >>> [e.tag for e in root.fin

Categories : Python

How do I handle whitespace with Python's elementtree?
This appears to be a known bug in xml.etree.ElementTree: http://bugs.python.org/issue17582. According to that bug report, this is correctly handled in lxml.etree: https://pypi.python.org/pypi/lxml/.

Categories : Python

Parsing XML with Python ElementTree with incorrect tags
This is standard ElementTree behavior. If the tags you're searching for are declared within a namespace, you have to specify that namespace when you search for those tags. However, you can do something like this: import xml.etree.ElementTree as ET tree = ET.parse('data.xml') root = tree.getroot() def prepend_ns(s): return '{http://www.w3.org/2005/Atom}' + s for entry in root.findall(prepend_ns('entry')): print 'Entry:' print ' Title: ' + entry.find(prepend_ns('title')).text print ' Author: ' + entry.find(prepend_ns('author')).find(prepend_ns('name')).text print ' URL: ' + entry.find(prepend_ns('link')).attrib['href'] print ' Summary: ' + entry.find(prepend_ns('summary')).text

Categories : Python

XML Python Choosing one of numerous attributes using ElementTree
You fail at .find('second-tag'), not on the .get. For what you want, and your idiom, BeautifulSoup shines. from BeautifulSoup import BeautifulStoneSoup soup = BeautifulStoneSoup(xml_string) whatyouwant = soup.find('second-tag')['status']

Categories : Python

Want to delete multiple tags with same tag name in XML using python elementtree?
remove takes an element as parameter, not a xpath. Instead of: root.remove(tag_name) you should have: elements = root.findall(tag_name) for element in elements: root.remove(element)

Categories : Python

XML Parsing issue in python using xml.etree.ElementTree
Don't parse xml with regular expressions! That won't work, use some xml parsing library instead, lxml for instance: edit: the code example now fetch top resources only, the loop over them and try to fetch "sub resources", this was made after OP request in comment from lxml import etree content = ''' YOUR XML HERE ''' root = etree.fromstring(content) # search for all "top level" resources resources = root.xpath("//Resource[not(ancestor::Resource)]") for resource in resources: # copy resource attributes in a dict mashup = dict(resource.attrib) # find child resource elements subresources = resource.xpath("./Resource") # if we find only one resource, add it to the mashup if len(subresources) == 1: mashup['resource'] = dict(subresources[0].attrib) # else

Categories : Python

Writing Python ElementTree to file throws TypeError
Seem following line is cause. print "ERROR: " + dept Change as follow and retry: print "ERROR: ", dept OR print "ERROR: " + str(dept) ADD Second argument to ET.SubElement should be str. Is deptElement is str? If deptElement is Element, use allDepts.append(deptElement). http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.SubElement http://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.append ADD 2 To reproduce error (Python 2.6): >>> from xml.etree import ElementTree as ET >>> allDepts = ET.Element('depts') >>> ET.SubElement(allDepts, ET.Element('a')) <Element <Element a at b727b96c> at b727b22c> >>> with open('a', 'wb') as f: ... tree = ET.ElementTr

Categories : Python

Is there a key for the default namespace when creating dictionary for use with xml.etree.ElementTree.findall() in Python?
Decided to take a look at the source code for the method. So as it turns out, the following code in xml.etree.ElementPath is doing the dirty work: def xpath_tokenizer(pattern, namespaces=None): for token in xpath_tokenizer_re.findall(pattern): tag = token[1] if tag and tag[0] != "{" and ":" in tag: try: prefix, uri = tag.split(":", 1) if not namespaces: raise KeyError yield token[0], "{%s}%s" % (namespaces[prefix], uri) except KeyError: raise SyntaxError("prefix %r not found in prefix map" % prefix) else: yield token pattern is the tag passed into findall(). If there is no : found in the tag, the tokenizer simply returns the tag back without

Categories : Python

Python escape character
Your problem is on this line: file_path = "F:ScriptsFilePathaddonsimport_test.py" Try one of these: file_path = r"F:ScriptsFilePathaddonsimport_test.py" file_path = "F:\ScriptsFilePath\addons\import_test.py" Or even: file_path = "F:/ScriptsFilePath/addons/import_test.py" (Yes, Windows accept forward slash as a file separator.) Ref: http://docs.python.org/2/reference/lexical_analysis.html#string-literals

Categories : Python

Python -SQL String Escape Wildcards
Double the % where you want to escape them (i.e. '%%r_%%'). Also, interpolate the string in the cursor.execute function like so: cursor.execute(QryString, matter)

Categories : Python

Python MySQLdb escape char: query works in MySQL but not in python MySQLdb
It turns out the confusion was in how Python printed the query string, combined with a bug in my own code. First, the bug: I incorrectly used str.replace() to replace the single literal backslash with an escaped double: sqlCmd.replace('\', '\\') So when Python showed the double-slash when printing the string, I assumed it had successfully replaced the single-slash. The correct code (in case anyone who reads this makes the same mistake) is: sqlCmd = sqlCmd.replace('\', '\\') The second source of confusion was that the Python interpreter uses __repr__() which automatically inserts an escape backslash for displaying but this escape backslash isn't actually in the original string. Python assumes you're smart enough to know this. Turns out I wasn't. ;-) A short additional explanation

Categories : Python

Python (and possibly others) - What is the escape character for a space?
the space is ok. and you are free to write the slash. if os.path.exists('C:/Program Files'): print 'yes' if os.path.exists(r'C:Program Files'): print 'yes' if os.path.exists('C:\Program Files'): print 'yes' all above are ok with or without a "r". @nneonneo reminded that the second one is dangerous without "r" because the backslash is used to escape.

Categories : Python

Next line escape character not working python
You can use rstrip(): >>> for i in content: ... print i.rstrip() ... abc def ghi The problem with your code is that it isn't doing what you would expect it to do. content is a list, and printing the list would just have ['abc ', etc]. You can use a for-loop (as I have shown) to go through each element in the list and individually print out all the elements on a separate line. I'm not exactly sure why you have print(' '), but I'm presuming that you come from another programming language. Python automatically adds a newline, so adding one is not needed :). Finally, rstrip() is needed to strip the newline, otherwise this would appear: >>> for i in L: ... print i ... abc def ghi

Categories : Python

Equivalent of python decode(string-escape) in c#
Looks if these methods helps System.Text.ASCIIEncoding.ASCII.GetBytes() System.Convert.ToBase64String() Convert.FromBase64String() Or what you may be looking for is http://stackoverflow.com/questions/11584148/how-to-convert-a-string-containing-escape-characters-to-a-string usually @ symbol before a string is what c# uses. If you can clarify your questions it will be helpful

Categories : C#

Attribute error: function object has no attribute in python
Just to get this answered: def datapaths(ipaddress, testlogfile): # Unecessary code reomved (code, val) = datapaths.listDatapaths(mylib) # Unecessary code reomved You are trying to access an attribute of a function you've defined, but most likely not set. I think you need to rexamine your code.

Categories : Python

Escape (Insert backslash) before brackets in a Python string
You've already found the most Pythonic way, regex provides a not so readable solution: >>> import re >>> s = u'LastName FirstName (Department / Subdepartment)' >>> print re.sub(r'([()])', r'\1', s) LastName FirstName (Department / Subdepartment)

Categories : Python

A for loop using colons
That is an enhanced for loop, introduced with the Java SE platform in version 5.0, It is a simpler way of iterating over the elements of an array or Collection. They can be used when you wish to step through each element of the array in first-to-last order, and you do not need to know the index of the current element. Assuming this.getPossibleMoves(color) returns a Move[] array.This code : for (final Move move : this.getPossibleMoves(color)) { // do something.... } is implicitly equivalent to : for (int index=0;index<this.getPossibleMoves(color).length;index++) { final Move move = this.getPossibleMoves(color)[index]; // do something.... } Suggested Reading: The For-Each Loop. Using Enhanced For-Loops Enhanced for each loop iteration control

Categories : Java

SOAP query variable, to escape or not to escape?
It's really hard to understand from your question what you would want to escape, but let's walk through it. Typically, you want to Filter-In, Escape-Out. What that means, is when you accept input from anywhere outside your application, you want to filter it. But what does filter mean? It means ensure that it's valid. If you're expecting an alpha-numeric user-name, and someone passes in one with symbols, reject it. That's filtering... Then, when you go to output data, you want to escape it specifically for the context you're outputting. So if you're writing it in an HTML body, you'd use something like html_special_chars. If you're sending to a database, you'd either use a prepared statement or escape it using a db-specific escaping algorithm. So where does that leave us in your situa

Categories : PHP

Semi-colons in URL changes to %3b via .htaccess
Your first rule is doing this. When I click on your second link, since it doesn't end with a slash or a period, it redirects me to the same URI except with a slash. Try using the NE flag so that the semicolons don't get encoded: RewriteCond %{REQUEST_URI} !(/$|.) RewriteRule (.*) %{REQUEST_URI}/ [R=301,L,NE] Not sure why the dev site isn't doing the same thing, unless it's missing the redirect rule.

Categories : Htaccess

can a css line contain multiple colons?
Yes. If you specify a filter (IE) it contains a second colon. Example: filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fad59f', endColorstr='#fa9907') Any CSS property that takes a url could easily contain http: Example: background-image: url("http://example.com/image.jpg");

Categories : CSS

VBA HTTP GET request - cookies with colons
I did a bit of testing with WinHttpRequest and I came up with the following code: Dim objReq As WinHttp.WinHttpRequest Set objReq = New WinHttp.WinHttpRequest objReq.Option(WinHttpRequestOption_EnableRedirects) = True objReq.Open "GET", "http://www.example.com", False objReq.setRequestHeader "Cookie", "abcd=cookie:containing:colons" objReq.send I did notice i got the same error that you posted when I forgot to include the "http://" in the url. I hope this helps!

Categories : Vba

How is this struct referenced? And what are the colons (:) at the bottom?
This form of initialization appears to be a GNU extension. clang++ tells me: quirk.cpp:10:5: warning: use of GNU old-style field designator extension [-Wgnu-designator] The standard (at least in C99, not in C++) equivalent of this is the .field = <expr> syntax: static struct { uint16_t foo; uint16_t trim2; uint16_t foo1; uint16_t bar1; } elevon = { .foo = 1500, .trim2 = 1500, .foo1 = 1500, .bar1 = 1500 }; So, all this code does is declaring and initializing the variable elevon of which the type is an anonymous struct, and initializing it (its members) with values.

Categories : C++

What does double colons and underscore mean in Joomla?
The double colon is called the scope resolution operator and is used for calling static class methods or properties. Underscore doesnt mean anything but _() is usually used for string translations.

Categories : PHP

Plotting CSV with semi-colons and time formatted data with Gnuplot
First, apparently you can set the delimiter thus: set datafile separator ";" Then set the time format for your first file, and set x to be a time axis: set timefmt "%d.%m.%y - %H:%M:%S" set xdata time Plot the first file plot "data1.csv" using 1:2 The second file x values don't seem to have a date format, but instead perhaps seconds elapsed? For that, just do set datafile separator ";" plot "data2.csv" using 1:2 and don't set xdata time. Then you should have an x axis in seconds. If you need to plot both at the same time, it would be simplest to pre-process one to look like the other.

Categories : Csv

How do I split this line (in JavaScript) on the colons, except if the colon is preceded by http or https?
JavaScript doesn't have lookbehinds :( Hack: Reverse the string var reverse = function(s) { return s.split('').reverse().join(''); }; var parts = reverse(line).split( /:(?!ptth)/ ).map(reverse).reverse(); Tweaked problem #1: Match colon not followed by // var parts = line.split( /:(?!//)/ ); Tweaked problem #2: Match only the last two colons var parts = line.match( /(.*):(.*):(.*)/ ) ; parts.shift();

Categories : Javascript

Bash Error - Program errors on the lines with the double semi-colons
Your while syntax is messed up. You need a condition between the while and the do. That's probably screwing up the parsing of the case statement.

Categories : Bash

how to test restful web service with parameters separated by semi colons and requiring authentication using soapui
You should be able to add parameters as MATRIX to the REST Service. Try to add a parameter to the REST Service, change the style from QUERY(default) to MATRIX. Refer this snapshot.

Categories : Rest

Python: octal escape character 33 from a dictionary value translates in a print statement to a UTF-8 character instead
I went through your source code and I think the probelm is with the color definition within the dictionary. If you observe carefully, your dictionary value for a color is something like 33[1,30m for white color. However it should be 33[1;30m. Note that you are using a ',(comma) character instead of ';(semicolon) character. As a test I created a subset of the color dictionary and ran these tests. >>> color = {'white' :'33[1;37m', 'yellow':'33[1;33m', 'off' : '33[0;0m'} >>> print color['white'] + 'string' + color['off'] string #this string is white in color >>> print color['yellow'] + 'string' + color['off'] string #this string is yellow in color >>> color['yellow'] = '33[1,33m' #incorrect color code - using a , character instead of ; >>> prin

Categories : Python

Parse XML with ElementTree
Iterate over parents, then find children of the parents. for parent in tree.findall('./Parent'): children = [child for child in parent.findall('./Child')] print '{} has {}'.format(parent.get('name'), ' '.join(c.get('name') for c in children)) Response to the comment Using lxml, you can access parent node with getparent() method. import lxml.etree tree = lxml.etree.parse('1.xml') for child in tree.findall('./Parent/Child'): print '{} has {}'.format(child.getparent().get('name'), child.get('name'))

Categories : Python

Perl regex to match alt attribute as mandatory but sometimes alt attribute comes before src attribute and sometimes after src attribute
Does it have to be just one regex only? use Data::Dumper; my $s = q{<img rel="relfoo" src="srcfoo">}; my @m; $s =~ m{ <img s+ ( ((w+)(?{push @m, $^N})) = "( ([^"]*) (?{push @m, $^N}) )" s* )+ > }x; my %h = @m; print Dumper \%h; die "alt is mandatory.. " if !exists $h{alt}; output $VAR1 = { 'rel' => 'relfoo', 'src' => 'srcfoo' }; alt is mandatory..

Categories : Regex

Why does ElementTree reencode my string?
That is normal Python behaviour; you are looking at a unicode string representation, one that can be pasted back into a Python interpreter without encoding problems as any non-ASCII or non-printable byte is represented as an escape code. Note that the newlines are also represented by their escape code. Use print dm.text to write out the byte values without Python string literal representation: >>> text = u'<?xml version="1.0" encoding="UTF-8"?> <string>Rxe9sumxe9</string> ' >>> print text <?xml version="1.0" encoding="UTF-8"?> <string>Résumé</string> The codepoints are unicode codepoints, but because they are below U+0100 Python represents them with the x.. escape code. Higher codepoints would use the u.... escape code

Categories : Python

ElementTree.parse runs out of memory
I don't know Python, but I suggest checking what type of parser ElementTree.parse uses. If it's a DOM parser, try to find a SAX parser and use that instead. SAX parsers are more efficient as they don't store the entire DOM tree.

Categories : Python

remove element from elementtree/list
You are only removing references to the elements from your list. You need to call .remove() on the parent element instead. ElementTree does not retain parent pointers; given a CONFIG element alone you cannot go back the VIEW element that is its parent. This means you need to retain a reference to the parent as well. Loop over the VIEW elements, then in a nested loop find the CONFIG elements you want to remove and with the VIEW parent still available, call .remove() to remove a child element from that parent.

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.