Reading XML file and fetching its attributes value in Python

Here’s an lxml snippet that extracts an attribute as well as element text (your question was a little ambiguous about which one you needed, so I’m including both): from lxml import etree doc = etree.parse(filename) memoryElem = doc.find(‘memory’) print memoryElem.text # element text print memoryElem.get(‘unit’) # attribute You asked (in a comment on Ali Afshar’s … Read more

How to convert XML to JSON using C#/LINQ?

using System; using System.Linq; using System.Web.Script.Serialization; using System.Xml.Linq; class Program { static void Main() { var xml = @”<Columns> <Column Name=””key1″” DataType=””Boolean””>True</Column> <Column Name=””key2″” DataType=””String””>Hello World</Column> <Column Name=””key3″” DataType=””Integer””>999</Column> </Columns>”; var dic = XDocument .Parse(xml) .Descendants(“Column”) .ToDictionary( c => c.Attribute(“Name”).Value, c => c.Value ); var json = new JavaScriptSerializer().Serialize(dic); Console.WriteLine(json); } } produces: {“key1″:”True”,”key2″:”Hello World”,”key3″:”999″} … Read more

Read a XML (from a string) and get some fields – Problems reading XML

You should use LoadXml method, not Load: xmlDoc.LoadXml(myXML); Load method is trying to load xml from a file and LoadXml from a string. You could also use XPath: XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); string xpath = “myDataz/listS/sog”; var nodes = xmlDoc.SelectNodes(xpath); foreach (XmlNode childrenNode in nodes) { HttpContext.Current.Response.Write(childrenNode.SelectSingleNode(“//field1”).Value); }

Python element tree – extract text from element, stripping tags

If you are running under Python 3.2+, you can use itertext. itertext creates a text iterator which loops over this element and all subelements, in document order, and returns all inner text: import xml.etree.ElementTree as ET xml=”<tag>Some <a>example</a> text</tag>” tree = ET.fromstring(xml) print(”.join(tree.itertext())) # -> ‘Some example text’ If you are running in a lower … Read more

DTD prohibited in xml document exception

First, some background. What is a DTD? The document you are trying to parse contains a document type declaration; if you look at the document, you will find near the beginning a sequence of characters beginning with <!DOCTYPE and ending with the corresponding >. Such a declaration allows an XML processor to validate the document … Read more