Best xml questions in September 2010

What are the advantages of creating web pages with XML instead of HTML?

9 votes

From time to time, I see web pages whose content is solely written in XML (not HTML or XHTML). These pages usually have some style sheets (either XSLT or CSS) attached to them which makes them look like any other ordinary web page.

My question is, what are the advantages of such an approach (if any), and why would anyone choose to work this way?

EDIT: If this is a good thing, why is it not widespread?

EDIT 2: Thanks everyone for the great responses. They really enlightened me. I also found this question whose content is also related.

It's easier to generate it programmatically and reuse it for other purposes than displaying as webpage.


Update:

EDIT: If this is a good thing, why is it not widespread?

Not everyone needs to generate it programmatically or reuse it for other purposes than displaying as webpage. It's then easier to use plain HTML.

Scala: jaxb or similar?

7 votes

As a java programmer I'm quite comfortable with using JAXB and similar, for example to construct object from a XML spec.

I'm sure I can make JAXB work nice in scala, but I wonder if that is the scala way of doing it, or if there is some better/smarter way, especially since XML is almost part of the language / it's internal libraries.

So, given that I want to create a set of object form a XML spec, what's the recommended way to do this in scala?

For pure Scala, there is scalaxb. It generates case classes and parser based on Scala parser combinators. It's still quite young, but if you steer clear of the advanced features of XML Schema it is quite usable.

Why isn't the HL7 standard using XML?

7 votes

I am new to HL7 and the first thing that came to my mind was, why isn't this format using XML instead? There are a handful of parsers and there are some serious inconsistencies among vendors.


For those new to the health care software business I recommend this read http://www.interfaceware.com/hl7_version2x.html

HL7 version 3 is using XML. Earlier versions of HL7 are a health care specific derivative of a pipe delimited format (IIRC its called ER7, not sure though).

Theres nothing particularly wrong with the pipe delimited format. In many ways the newer XML variations are harder to use. It may be old, but for the most part it works and it is well understood.

Writing an RSS reader in Java

6 votes

I'm trying to write a basic RSS reader for a class project. Our book shows an example by walking the DOM tree. Is that a decent approach for an RSS reader? Would I just ignore certain tags that are of uninterest to me and not to be used by the RSS Reader? Thanks.

It's one of two common approaches, so yes. And yes, ignoring tags that are not of interest is a good way to handle it. If you don't need it, no need to take note of it. If you know in advance exactly what tags you need, you probably don't need to walk the entire DOM tree.

You could also use a SAX parser which would probably be faster and less memory intensive, though probably not necessary in this case, depending on how many results you wish to have in the feed.

Transform SQL table to XML with column as parent node

6 votes

I'm trying to transform a table to an XML struture and I want one of the columns in my table to represent a parent node and the other column to represent a child node.

I have got part of the way but I don't have the complete solution. I need the TABLE_NAME column to transform to a xml parent node and the COLUMN_NAME column to transform as child nodes. If I execute the following I get the nesting but I also get multiple parent nodes.

select
 TABLE_NAME AS 'tn',
 COLUMN_NAME AS 'tn/cn'
from (
 select 'TABLE_A' AS TABLE_NAME, 'COLUMN_1' AS COLUMN_NAME
 UNION ALL
 select 'TABLE_A' AS TABLE_NAME, 'COLUMN_2' AS COLUMN_NAME
 UNION ALL
 select 'TABLE_B' AS TABLE_NAME, 'COLUMN_1' AS COLUMN_NAME
 UNION ALL
 select 'TABLE_B' AS TABLE_NAME, 'COLUMN_2' AS COLUMN_NAME
) x
for xml path(''), ROOT('datatable')

OUPUT>>>

<datatable>
  <tn>TABLE_A<cn>COLUMN_1</cn></tn>
  <tn>TABLE_A<cn>COLUMN_2</cn></tn>
  <tn>TABLE_B<cn>COLUMN_1</cn></tn>
  <tn>TABLE_B<cn>COLUMN_2</cn></tn>
</datatable>

DESIRED OUTPUT >>>

<datatable>
  <TABLE_A>
   <cn>COLUMN_1</cn>
   <cn>COLUMN_2</cn>
  </TABLE_A>
  <TABLE_B>
    <cn>COLUMN_1</cn>
    <cn>COLUMN_2</cn>
  </TABLE_B>
</datatable>

Is this possible or am I dreaming? and is it possible without XML EXPLICIT or is this the kind of thing EXPLICIT is there for?

The other possiblity I've been trying is to stuff the xml and then apply an xquery, but no joy with that yet.

Thanks,

Gary

As others have mentioned, FOR XML doesn't allow you to dynamically name nodes. The node names have to be constants by the time the query itself is compiled. You can work around this with dynamic sql but then you end up with code that gets harder and harder to read.

An alternative would be to manually generate the talbe name nodes and CAST into XML:

Setup:

CREATE TABLE a (table_name VARCHAR(20), column_name VARCHAR(20)
INSERT INTO a VALUES ('TABLE_A', 'COLUMN_1')
INSERT INTO a VALUES ('TABLE_A', 'COLUMN_2')
INSERT INTO a VALUES ('TABLE_B', 'COLUMN_1')
INSERT INTO a VALUES ('TABLE_B', 'COLUMN_2')

Execute:

SELECT CAST(
      '<' + table_name + '>'
    + (SELECT c.column_name as 'CN'
         FROM a c
        WHERE c.table_name = p.table_name
       FOR XML PATH('')) 
    + '</' + table_name + '>'
    AS XML)
  FROM a p
GROUP BY p.table_name
FOR XML PATH(''), ROOT('datatable')

Produces:

<datatable>
  <TABLE_A>
    <CN>COLUMN_1</CN>
    <CN>COLUMN_2</CN>
  </TABLE_A>
  <TABLE_B>
    <CN>COLUMN_1</CN>
    <CN>COLUMN_2</CN>
  </TABLE_B>
</datatable>

Is there a JavaScript API for XML binding - analog to JAXB for Java?

6 votes

In Java, we work a lot with JAXB2. Object<->XML mappings are defined as annotations in Java classes:

@XmlRootElement(name="usertask", namespace="urn:test")
public class UserTask
{
    @XmlElement(namespace="urn:test")
    public String getAssignee() { ... }

    public void setAssignee(String assignee) { ... }
}

JAXB runtime can read these annotations and create unmarshaller to parse XML into an object instance or marshall an object into XML.

JAXB ships a schema compiler (XJC) which can generate annotated classes out of XML Schemas, which is another great feature.


Lately we've been working a lot with client-side JavaScript. An we also need XML processing there. For example, we need to parse WPS documents like this one. These documents also comply to different XML schemas (here's the WPS 1.0.0 schema for the sample XML). It would be great to work with JavaScript objects instead of XML, this saves really huge amount of effort. In some cases we can use JSON-based solutions like DWR, but in many cases we do have to process XML on the client-side.

My question is:

Is there some analog of JAXB for JavaScript?

Some tool which would compile an XML Schema into some XML<->object mapping and provide a runtime to convert between XML and JavaScript objects?

I could easily imagine mappings generated in a form like:

UserTask = new JSXML.XmlRootElement({
  name: "usertask",
  namespace: "urn:test",
  properties: [
    {
      assignee: new JSXML.XmlElement({
        name: "assignee",
        namespace: "urn:test",
        type: new JSXML.XSD.String()
      })
    }
  ]
});

And this should be pretty enough to build unmarshaller or marshaller.

How about JSON support for JAXB? Reuse your current JAXB annotated model classes but output JSON from your REST endpoints.

Current versions of Jersey support this (via the jersey-json module) with JSONJAXBContext.

You could also try Jackson's JAXB and JAX-RS support.

Copying an XSLT variable

6 votes

I'm working on an Umbraco XSL Stylesheet and I am pretty stuck.

Basically, I have a parameter that I test and use it's value if it's present, otherwise I use the default parameter $currentPage.

Here are the parameters

<xsl:param name="source" select="/macro/sourceId" />
<xsl:param name="currentPage" />

Here's the variable

<xsl:variable name="current">
    <xsl:choose>
        <xsl:when test="$source &gt; 0">
            <xsl:copy-of select="umbraco.library:GetXmlNodeById($source)" />
        </xsl:when>
        <xsl:otherwise>
            <xsl:copy-of select="$currentPage" />
        </xsl:otherwise>
    </xsl:choose>
</xsl:variable>

And here's where I use it

<xsl:for-each select="msxml:node-set($source)/ancestor-or-self::* [@isDoc and @level=$level]/* [@isDoc and string(umbracoNaviHide) != '1']">
... code here ...
</xsl:for-each>


In a nutshell

This works

<xsl:variable name="source" select="$currentPage" />

This doesn't

<xsl:variable name="source">
  <xsl:copy-of select="$currentPage" /> <!-- Have tried using <xsl:value-of /> as well -->
</xsl:variable>

So how do you copy a variable without using the select="" attribute.

UPDATE: I've tried using another approach (see below) but I get a variable out of scope exception.

<xsl:choose>
    <xsl:when test="$source &gt; 0">
        <xsl:variable name="current" select="umbraco.library:GetXmlNodeById($source)" />
    </xsl:when>
    <xsl:otherwise>
        <xsl:variable name="current" select="$currentPage" />
    </xsl:otherwise>
</xsl:choose>

Generally, this expression selects one of two nodesets, based on whether a given condition is true() or false():

$ns1[$cond] | $ns2[not($cond)]

In your case this translates to:

    umbraco.library:GetXmlNodeById($source) 
|
    $currentPage[not(umbraco.library:GetXmlNodeById($source))]

The complete <xsl:variable> definition is:

<xsl:variable name="vCurrent" select=
"        umbraco.library:GetXmlNodeById($source) 
    |
        $currentPage[not(umbraco.library:GetXmlNodeById($source))]
"/>

This can be written in a more compact way:

<xsl:variable name="vRealSource" select="umbraco.library:GetXmlNodeById($source)"/>

<xsl:variable name="vCurrent" select=
    "$vRealSource| $currentPage[not($vRealSource)]"/>

SOAP-proxy in Scala - what do I need?

5 votes

I'm trying to write a program in Scala, that will accept SOAP-requests, get the response from the real server (or read it from the local disc) and return the data to the original client.

I'm new to the java/scala ecosystem, so I have no clue, what libraries to choose. I heard Scala's XML-handling is quite nice, so I don't know, whether I should use some enterprisey soap-library/framework like jax-ws, jboss-ws, axis, cxf, xmlbeans, etc.

Basically, I just need

  • a library, that accepts the requests (currently, I'm looking at jetty, but I'd prefer something that natively supports actors. scala-http seems to cover that, but isn't production-ready or maintained, for that matter)
  • some library to request the data from the other server (something like curl, libwww-perl for java/scala)
  • a build system (ant? sbt?)
  • an IDE (I'm used to eclipse, but IntelliJ's scala support is supposed to be better)
  • a tool to test it (currently, I'm using SoapUI)

SOAP is truly a hideous specification, with lots of potential for unusual fringe behaviour. While it's true that XML support in Scala would help you write such a library from scratch, it would still be a major effort (depending on how much of the spec you need).

Likewise, Jetty has years of development behind it; dealing with performance demands and other unexpected behaviour that you probably haven't considered... Even Scala's best-known web framework, Lift, runs atop a Java web server for these very reasons. It still works very happily with actors.

So, at this moment in time, you're almost certainly better off using a tried and tested solution with a Java web server and an off-the-shelf Java SOAP Library. The effort to add a thin Scala wrapper around these will be far less than the effort to build these things from scratch.

For the build system, sbt is the most powerful tool presently available for Scala, but you may need to fall back to Maven if this is needed for code generation by your chosen SOAP library.

Finally, for the choice of editor. If you're happy using Emacs, then the Ensime plugin is just amazing. If a more conventional Java IDE is to your liking, then IntelliJ currently seems to be the most stable option, though be aware that this could change very quickly.

Accessing XML attributes with namespaces

5 votes

How one can access attributes with namespaces? My XML data are in a form

val d = <z:Attachment rdf:about="#item_1"></z:Attachment>

but the following does not match the attribute

(d \\ "Attachment" \ "@about").toString

If I remove the namespace component from the attribute's name then it works.

val d = <z:Attachment about="#item_1"></z:Attachment>
(d \\ "Attachment" \ "@about").toString

Any idea how to access attributes with namespaces in Scala?

The API documentation refers to the following syntax ns \ "@{uri}foo".

In your example there is no namespace defined, and it seems Scala considers your attribute as unprefixed. See d.attributes.getClass.

Now if you do this:

val d = <z:Attachment xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" rdf:about="#item_1"></z:Attachment>

Then:

scala> d \ "@{http://www.w3.org/1999/02/22-rdf-syntax-ns#}about"
res21: scala.xml.NodeSeq = #item_1

scala> d.attributes.getClass
res22: java.lang.Class[_] = class scala.xml.PrefixedAttribute

Simple conversion between java.util.Date and XMLGregorianCalendar

5 votes

I'm looking for a simple method of converting between java.util.Date and javax.xml.datatype.XMLGregorianCalendar in both directions.

Here is the code that I'm using now:

import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 * Utility class for converting between XMLGregorianCalendar and java.util.Date
 */
public class XMLGregorianCalendarConverter {  

    /**
     * Needed to create XMLGregorianCalendar instances
     */
    private static DatatypeFactory df = null;
    static {
        try {
            df = DatatypeFactory.newInstance();
        } catch (DatatypeConfigurationException dce) {
            throw new IllegalStateException(
                "Exception while obtaining DatatypeFactory instance", dce);
        }
    }  

    /**
     * Converts a java.util.Date into an instance of XMLGregorianCalendar
     *
     * @param date Instance of java.util.Date or a null reference
     * @return XMLGregorianCalendar instance whose value is based upon the
     *  value in the date parameter. If the date parameter is null then
     *  this method will simply return null.
     */
    public static XMLGregorianCalendar asXMLGregorianCalendar(java.util.Date date) {
        if (date == null) {
            return null;
        } else {
            GregorianCalendar gc = new GregorianCalendar();
            gc.setTimeInMillis(date.getTime());
            return df.newXMLGregorianCalendar(gc);
        }
    }

    /**
     * Converts an XMLGregorianCalendar to an instance of java.util.Date
     *
     * @param xgc Instance of XMLGregorianCalendar or a null reference
     * @return java.util.Date instance whose value is based upon the
     *  value in the xgc parameter. If the xgc parameter is null then
     *  this method will simply return null.
     */
    public static java.util.Date asDate(XMLGregorianCalendar xgc) {
        if (xgc == null) {
            return null;
        } else {
            return xgc.toGregorianCalendar().getTime();
        }
    }
}

Is there anything simpler, like some API call that I have overlooked?

Converting between a standard XML date/time and a Java date object seems like a pretty routine task and I'm surprised that I have to write this code at all.

Any suggestions?

NOTES: My JAXB classes are autogenerated from a schema. The build process on my project does not allow for me to make manual changes to the generated classes. The xs:dateTime elements are being generated by XJC as XMLGregorianCalendar in the JAXB classes. The schema is extended and tweaked periodically, so I am allowed to make limited changes to the schema XSD file.

UPDATE ON SOLUTION: The solution proposed by Blaise has allowed me to take XMLGregorianCalendar out of the mix and deal with java.util.Calendar objects instead. By adding a JAXB binding clause at the top of my schema file, XJC is able to generate more appropriate mappings for xs:dateTime in my JAXB classes. Here are some snippets that show the modifications in my XSD file.

The root element in the XSD file:

<xs:schema xmlns:mydata="http://my.example.com/mydata" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" targetNamespace="http://my.example.com/mydata" elementFormDefault="unqualified" attributeFormDefault="unqualified" version="0.2" xml:lang="en" jaxb:version="2.0">

JAXB binding annotation block, inserted immediately after root element in XSD:

<xs:annotation>
    <xs:appinfo>
        <jaxb:globalBindings>
            <jaxb:javaType name="java.util.Calendar" xmlType="xs:dateTime" parseMethod="javax.xml.bind.DatatypeConverter.parseDateTime" printMethod="javax.xml.bind.DatatypeConverter.printDateTime" />
        </jaxb:globalBindings>
    </xs:appinfo>
</xs:annotation>

Since the XML xs:dateTime field also stores timezone, it might be better for me to work with Calendar instead of Date anyway since Calendar objects have a pretty good API for working with locales and timezones. In any case, I'm much happier to deal with Calendar objects instead of XMLGregorianCalendar. No need for the conversion methods that I listed above anymore. I didn't get all the way to java.util.Date, but close enough!

Why not use an external binding file to tell XJC to generate java.util.Date fields instead of XMLGregorianCalendar?

Also see: - http://weblogs.java.net/blog/kohsuke/archive/2006/03/how_do_i_map_xs.html

LINQ to XML: What is the most effective way to move nodes up and down

5 votes

I need to move sibling nodes before and after certain nodes. Here is the code im working with

<tabs>
     <tab>
          <name>Overview</name>
     </tab>
     <tab>
          <name>Testing</name>
     </tab>
     <tab>
          <name>Performance</name>
     </tab>
     <tab>
          <name>Braking</name>
     </tab>
</tabs>

I would like to move the tab with testing in it above Overview. How would I go about this using linq to XML?

Sorry, this is VB.NET and XML Literals, but it can be done old school in C#. The idea here is to use the Reverse extention method:

Sub Main()
        Dim tab = <tabs>
                      <tab>
                          <name>Overview</name>
                      </tab>
                      <tab>
                          <name>Testing</name>
                      </tab>
                      <tab>
                          <name>Performance</name>
                      </tab>
                      <tab>
                          <name>Braking</name>
                      </tab>
                  </tabs>
        Console.WriteLine(SwapElements("Testing", "Performance", tab).ToString)
        Console.ReadLine()
    End Sub
    Function SwapElements(ByVal firstElement As String, ByVal secondElement As String, ByVal tab As XElement) As XElement
        Dim swapped = tab.Elements.Where(Function(e) e.Value = firstElement Or e.Value = secondElement).Reverse
        Dim middle = tab.Elements.SelectMany(Function(e) e.ElementsAfterSelf.Where(Function(f) e.Value = firstElement).TakeWhile(Function(g) g.Value <> secondElement))
        swapped.ElementAt(0).AddAfterSelf(middle)
        Return <<%= tab.Name %>>
                   <%= tab.Elements.Select(Function(e) e.ElementsBeforeSelf.Where(Function(f) e.Value = firstElement)) %>
                   <%= swapped %>
                   <%= tab.Elements.Select(Function(e) e.ElementsAfterSelf.Where(Function(f) e.Value = secondElement)) %>
               </>
    End Function

How I can repeat an action X times with XSLT

5 votes

I've to populate a total of 20 elements with XSLT. In my XML code I have a <select> with the values, there is anyway to not to write 20 forms?

My XML:

<output>
    <select>
        <id>1</id>
        <name>One</name>
    </select>
    <select>
        <id>2</id>
        <name>Two</name>
    </select>
    <select>
        <id>3</id>
        <name>Three</name>
    </select>
    <!-- An more -->
</output>

My XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   
    <xsl:template match="/">
        <html>

            <body>
        <select name="values[]">
            <option value="0"> </option>
            <xsl:for-each select="output/select">
                <option>
                    <xsl:attribute name="value"><xsl:value-of select="id"></xsl:attribute>
                    <xsl:value-of select="name" />
                </option>
            </xsl:for-each>
        </select>
            </body>

        </html>
    </xsl:template>
</xsl:stylesheet>

Desired output:

<html>
    <body>

        <select name="values[]">
            <option value="0"> </option>
            <option value="1">One</option>
            <option value="2">Two</option>
            <option value="3">Three</option>
        </select>
        <!-- But 20 times -->   

    </body>
</html>

First, use templates instead of for-each, then you can use a recursive template call to emulate a for loop (as seen here):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   
    <xsl:template match="/">
        <html>
        <body>

            <xsl:call-template name="selects">
               <xsl:with-param name="i">1</xsl:with-param>
               <xsl:with-param name="count">20</xsl:with-param>
            </xsl:call-template> 

        </body>    
        </html>
    </xsl:template>

    <xsl:template name="selects">
        <xsl:param name="i" />
        <xsl:param name="count" />

        <xsl:if test="$i &lt;= $count">
          <select name="values[]">
            <xsl:apply-template select="output/select" />
          </select?
        </xsl:if>

        <!--begin_: RepeatTheLoopUntilFinished-->
        <xsl:if test="$i &lt;= $count">
            <xsl:call-template name="selects">
                <xsl:with-param name="i">
                    <xsl:value-of select="$i + 1"/>
                </xsl:with-param>
                <xsl:with-param name="count">
                    <xsl:value-of select="$count"/>
                </xsl:with-param>
            </xsl:call-template>
        </xsl:if>

    </xsl:template>

    <xsl:template match="output/select">
      <option>
        <xsl:attribute name="value">
            <xsl:value-of select="id">
        </xsl:attribute>
        <xsl:value-of select="name" />
      </option>
    </xsl:template>
</xsl:stylesheet>

How can I rename class-names via Xml attributes?

4 votes

Suppose I have an XML-serializable class called Song:

[Serializable]
class Song
{
    public string Artist;
    public string SongTitle;
}

In order to save space (and also semi-obfuscate the XML file), I decide to rename the xml elements:

[XmlRoot("g")]
class Song
{
    [XmlElement("a")]
    public string Artist;
    [XmlElement("s")]
    public string SongTitle;
}

This will produce XML output like this:

<Song>
  <a>Britney Spears</a>
  <s>I Did It Again</s>
</Song>

I want to rename/remap the name of the class/object as well. Say, in the above example, I wish to rename the class Song to g. So that the resultant xml should look like this:

<g>
  <a>Britney Spears</a>
  <s>I Did It Again</s>
</g>

Is it possible to rename class-names via xml-attributes?

I don't wish to create/traverse the DOM manually, so I was wondering if it could be achieved via a decorator.

Thanks in advance!

UPDATE: Oops! This time I really did it again! Forgot to mention - I'm actually serializing a list of Song objects in the XML.

Here's the serialization code:

    public static bool SaveSongs(List<Song> songs)
    {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Song>));
            using (TextWriter textWriter = new StreamWriter("filename"))
            {
                serializer.Serialize(textWriter, songs);
            }
    }

And here's the XML output:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfSong>
<Song>
  <a>Britney Spears</a>
  <s>Oops! I Did It Again</s>
</Song>
<Song>
  <a>Rihanna</a>
  <s>A Girl Like Me</s>
</Song>
</ArrayOfSong>

Apparently, the XmlRoot() attribute doesn't rename the object in a list context.

Am I missing something?

Checkout the XmlRoot attribute.

Documentation can be found here: http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlrootattribute(v=VS.90).aspx

[XmlRoot(Namespace = "www.contoso.com", 
     ElementName = "MyGroupName", 
     DataType = "string", 
     IsNullable=true)]
public class Group

UPDATE: Just tried and it works perfectly on VS 2008. This code:

[XmlRoot(ElementName = "sgr")]
public class SongGroup
{
    public SongGroup()
    {
       this.Songs = new List<Song>();
    }



[XmlElement(ElementName = "sgs")]
    public List<Song> Songs { get; set; }
}

[XmlRoot(ElementName = "g")]
public class Song
{
    [XmlElement("a")]
    public string Artist { get; set; }

    [XmlElement("s")]
    public string SongTitle { get; set; }
} 

Outputs:

<?xml version="1.0" encoding="utf-8"?>
<sgr xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www
.w3.org/2001/XMLSchema">
  <sgs>
    <a>A1</a>
    <s>S1</s>
  </sgs>
  <sgs>
    <a>A2</a>
    <s>S2</s>
  </sgs>
</sgr>

xml sample/app settings in xml

4 votes

can anyone help me to learn how to use XML. As a test i want to use XML instead of INI files for saving a program settings.

Thanks

Rigo, you can use the IXMLDocument interface or the TXMLDocument object to interact with a XML document.

You can check these links for more information about XML and Delphi

Check this sample code , to learn the basics about xml management using the IXMLDocument interface.

program Delphi_XmlSaveSettings;

{$APPTYPE CONSOLE}
uses
  ActiveX,
  SysUtils,
  XmlDoc,
  XmlIntf;
//this class mimic the basics functionalities of an TIniFile
//you can improve a lot the code adding exception handling and more methods for specifics tasks.
type
  TXMLSettings = class 
  private
    FFileName: string;
    FXMLDoc: IXMLDocument; //Main XMLObject
  public
    constructor Create(const FileName: string); overload;
    destructor  Destroy; override;
    function    ReadString(const Section, Key, default: string): string;
    procedure   WriteString(const Section, Key, Value: string);
    function    ReadInteger(const Section, Key: string; default: Integer): Integer;
    procedure   WriteInteger(const Section, Key: string; Value: Integer);
    function    ReadBoolean(const Section, Key: string; default: Boolean): Boolean;
    procedure   WriteBoolean(const Section, Key: string; Value: Boolean);
    function    ReadDouble(const Section, Key: string; default: Double): Double;
    procedure   WriteDouble(const Section, Key: string; Value: Double);
    function    ReadDateTime(const Section, Key: string; default: TDatetime): TDateTime;
    procedure   WriteDatetime(const Section, Key: string; Value: TDatetime);
    function    ReadDate(const Section, Key: string; default: TDatetime): TDateTime;
    procedure   WriteDate(const Section, Key: string; Value: TDatetime);
    procedure   Save;
  end;



constructor TXMLSettings.Create(const FileName: string);
begin
  inherited Create;
  FFileName       := FileName;
  FXMLDoc         := NewXMLDocument; //Create  aNew instance of a XML Document
  FXMLDoc.Encoding:= 'UTF-8'; //Set the encoding
  FXMLDoc.Options := [doNodeAutoIndent];//optional, is used to indent the Xml document

  if FileExists(FFileName) then
    FXMLDoc.LoadFromFile(FFileName)
  else
    FXMLDoc.AddChild('Root'); //Create the root Node
end;


destructor TXMLSettings.Destroy;
begin
  Save;
  inherited;
end;

function TXMLSettings.ReadBoolean(const Section, Key: string; default: Boolean): Boolean;
begin
  Result := Boolean(ReadInteger(Section, Key, Integer(default)));
end;

function TXMLSettings.ReadDate(const Section, Key: string; default: TDatetime): TDateTime;
begin
  Result := StrToDate(ReadString(Section, Key, DateToStr(default)));
end;

function TXMLSettings.ReadDateTime(const Section, Key: string; default: TDatetime): TDateTime;
begin
  Result := StrToDateTime(ReadString(Section, Key, DateTimeToStr(default)));
end;

function TXMLSettings.ReadDouble(const Section, Key: string;  default: Double): Double;
begin
  Result := StrToFloat(ReadString(Section, Key, FloatToStr(default)));
end;

function TXMLSettings.ReadInteger(const Section, Key: string; default: Integer): Integer;
begin
  Result := StrToInt(ReadString(Section, Key, IntToStr(default)));
end;

function TXMLSettings.ReadString(const Section, Key, default: string): string; 
var
  XMLNode: IXMLNode;
begin
  XMLNode := FXMLDoc.DocumentElement.ChildNodes.FindNode(Section);
  if Assigned(XMLNode) and XMLNode.HasAttribute(Key) then //Check if exist the Key
    Result := XMLNode.Attributes[Key]
  else
    Result := default;
end;

procedure TXMLSettings.Save;
begin
  FXMLDoc.SaveToFile(FFileName);
end;

procedure TXMLSettings.WriteBoolean(const Section, Key: string; Value: Boolean);
begin
  WriteInteger(Section, Key, Integer(Value));
end;

procedure TXMLSettings.WriteDate(const Section, Key: string; Value: TDatetime);
begin
  WriteString(Section, Key, DateToStr(Value));
end;

procedure TXMLSettings.WriteDatetime(const Section, Key: string;  Value: TDatetime);
begin
  WriteString(Section, Key, DateTimeToStr(Value));
end;

procedure TXMLSettings.WriteDouble(const Section, Key: string; Value: Double);
begin
  WriteString(Section, Key, FloatToStr(Value));
end;

procedure TXMLSettings.WriteInteger(const Section, Key: string; Value: Integer);
begin
  WriteString(Section, Key, IntToStr(Value));
end;

procedure TXMLSettings.WriteString(const Section, Key, Value: string);
var
  XMLNode: IXMLNode;
begin
  XMLNode := FXMLDoc.DocumentElement.ChildNodes.FindNode(Section);
  if not Assigned(XMLNode) then
  XMLNode := FXMLDoc.DocumentElement.AddChild(Section);
  XMLNode.Attributes[Key] := Value;
end;


Procedure SaveSettings; //Store the settings
Var
  AppSettings :  TXMLSettings;
begin
  AppSettings:=TXMLSettings.Create(ExtractFilePath(ParamStr(0))+'MySettings.xml');
  try
   AppSettings.WriteString('Server','Type','SQLServer');
   AppSettings.WriteString('Server','User','root');
   AppSettings.WriteInteger('Server','port',1433);
   AppSettings.WriteString('Server','IP','192.168.1.1');
   AppSettings.WriteString('Server','Database','Prod');
   AppSettings.WriteBoolean('Server','WindowsAuth',False);
   AppSettings.WriteDouble('Server','Latency',25.90892);
   AppSettings.WriteDatetime('Server','LastAccess',Now);
   AppSettings.WriteDate('Server','ActualDate',Now);
   AppSettings.Save;
  finally
  AppSettings.Free;
  end;
  Writeln('Settings Saved');
end;


Procedure ShowSettings;//Read the settings
Var
  AppSettings :  TXMLSettings;
begin
  AppSettings:=TXMLSettings.Create(ExtractFilePath(ParamStr(0))+'MySettings.xml');
  try
   Writeln(Format('Type         %s',[AppSettings.ReadString('Server','Type','')]));
   Writeln(Format('Port         %d',[AppSettings.ReadInteger('Server','port',0)]));
   Writeln(Format('IP           %s',[AppSettings.ReadString('Server','IP','')]));
   Writeln(Format('Database     %s',[AppSettings.ReadString('Server','Database','')]));
   Writeln(Format('WindowsAuth  %s',[BoolToStr(AppSettings.ReadBoolean('Server','WindowsAuth',True),True)]));
   Writeln(Format('Latency      %g',[AppSettings.ReadDouble('Server','Latency',0)]));
   Writeln(Format('LastAccess   %s',[DateTimeToStr(AppSettings.ReadDateTime('Server','LastAccess',Now-1))]));
   Writeln(Format('ActualDate   %s',[DateToStr(AppSettings.ReadDate('Server','ActualDate',Now-1))]));
  finally
  AppSettings.Free;
  end;
end;

begin
  try
    CoInitialize(nil); //only necesary in console applications
    try
      SaveSettings; //Save the sample settings
      ShowSettings; //Read the stored settings
      Readln;
    finally
    CoUninitialize; //only necesary in console applications
    end;
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
end.

Android: Error inflating class

4 votes

I'm new to Android development and I've been having an issue that I haven't been able to fix. I'm mostly using code from examples provided in the SDK so I'm not sure what's happening here. I'm simply trying to create a custom view GhostSurfaceCameraView that extends SurfaceView. Here's my class definition file GhostSurfaceCameraView.java:

public class GhostSurfaceCameraView extends SurfaceView implements
 SurfaceHolder.Callback {
 SurfaceHolder mHolder;
 Camera mCamera;

 GhostSurfaceCameraView(Context context) {
  super(context);

  // Install a SurfaceHolder.Callback so we get notified when the
  // underlying surface is created and destroyed.
  mHolder = getHolder();
  mHolder.addCallback(this);
  mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
 }

 public void surfaceCreated(SurfaceHolder holder) {
  // The Surface has been created, acquire the camera and tell it where
  // to draw.
  mCamera = Camera.open();
  try {
   mCamera.setPreviewDisplay(holder);
  } catch (IOException exception) {
   mCamera.release();
   mCamera = null;
   // TODO: add more exception handling logic here
  }
 }

 public void surfaceDestroyed(SurfaceHolder holder) {
  // Surface will be destroyed when we return, so stop the preview.
  // Because the CameraDevice object is not a shared resource, it's very
  // important to release it when the activity is paused.
  mCamera.stopPreview();
  mCamera.release();
  mCamera = null;
 }

 public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
  // Now that the size is known, set up the camera parameters and begin
  // the preview.
  Camera.Parameters parameters = mCamera.getParameters();
  parameters.setPreviewSize(w, h);
  parameters.set("orientation", "portrait");
  // parameters.setRotation(90); // API 5+
  mCamera.setParameters(parameters);
  mCamera.startPreview();
 }}

And this is in my ghostviewscreen.xml:

<com.alpenglow.androcap.GhostSurfaceCameraView android:id="@+id/ghostview_cameraview"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"/>

Now in the activity I made:

protected void onCreate(Bundle savedInstanceState) {

  try
  {
   super.onCreate(savedInstanceState);
         setContentView(R.layout.ghostviewscreen);
  }

When setContentView gets called, an exception is thrown:

Binary XML file 09-17 22:47:01.958: ERROR/ERROR(337): ERROR IN CODE: android.view.InflateException: Binary XML file line #14: Error inflating class com.alpenglow.androcap.GhostSurfaceCameraView

Can anyone tell me why I get this error? Thanks

I think I figured out why this wasn't working. I was only providing a constructor for the case of one parameter 'context' when I should have provided a constructor for the two parameter 'Context, AttributeSet' case. I also needed to give the constructor(s) public access. Here's my fix:

public class GhostSurfaceCameraView extends SurfaceView implements SurfaceHolder.Callback {
        SurfaceHolder mHolder;
        Camera mCamera;

        public GhostSurfaceCameraView(Context context)
        {
            super(context);
            init();
        }
        public GhostSurfaceCameraView(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            init();
        }
        public GhostSurfaceCameraView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }

Creating Chart using javascript

4 votes

I need to create chart using javascript. should be look like as in link below (click play to see chart sample):

Please suggest me which control should i use/purchase, which allows me to create chart in such style shown in link. chart data will be in xml format and i am asp.net developer thanks

For charting in HTML5 pages is good to use javascript library. I recomand these charting.

this one is like your charting.. http://www.jqplot.com/tests/OHLCTests.php http://code.google.com/apis/chart/docs/gallery/compound_charts.html#candlestick_charts

Others http://www.splashnology.com/blog/javascripts/290.html http://www.highcharts.com/ http://developer.yahoo.com/yui/examples/charts/index.html