Fetching xml node nth value using Xpath

HI Experts ,
with reference to below question, i have one more doubt.
https://social.msdn.microsoft.com/Forums/en-US/f894e5e2-8926-4604-9171-616da3f00cd7/xpath-to-fetch-value-in-flatfile-schema?forum=biztalkgeneral
I used below xpath to fetch nth value of full repeating message nodes
indexStr = System.Convert.ToString(index);DATE=xpath(In_FF, "string(//*[local-name() = 'Details']["+indexStr+"])/*[local-name()='DATE'])");index=index + 1;
and i got below error, can any help me in this?
Exception thrown from: segment 2, progress 43
Inner exception: 'string(//*[local-name() = 'Details'][1])/*[local-name()='DATE'])' has an invalid token.
Exception type: XPathException
Source: System.Xml
Target Site: MS.Internal.Xml.XPath.AstNode ParseXPathExpresion(System.String)
The following is a stack trace that identifies the location where the exception occured

your XPATH expression is WRONG.
it should be
DATE=xpath(In_FF,
"string(//*[local-name() = 'Details']["+indexStr+"]/*[local-name()='DATE'])");
There is NO ")" after ["+indexStr+"].
The more reliable way is to use a string variable and use the System.String.Format() call as below
xPathExpr = System.String.Format("string(//*[local-name() = 'Details'][{0}]/*[local-name()='DATE'])", index);
DATE=xpath(In_FF, xPathExpr);
The "invalid token" is because of the mismatched ")" in your XPATH Expression.
Regards.

Similar Messages

  • Convertion of XML node to string using Xquery transformation in OSB

    How to convert XML node to string using a built in function using Xquery transformation in OSB? In BPEL we have the Xpath extension function ora:getContentAsString() to do the same.

    fn:bea-serialize() function converts xml node to string. but it assigns namespace prefix in every xml node during the conversion. So is there any function to remove the namespace prefix from XML node using Xquery built in function?

  • Want to get id's value using xpath.

    Hi all,
    I want to get id attribute's value using xpath.
    my xml file as follows:
    <book>
         <person id="1">
                <first id="2">Kiran</first>
                <last id="3">Pai
                        <name id="4">das</name>
                </last>
                <age id="5">22</age>
         </person>
         <person id="6">
                <first id="7">Bill</first>
                <last id="8">Gates</last>
                <age id="9">46</age>
         </person>
         <person id="10">
                <first id="11">Steve</first>
                <last id="12">Jobs</last>
                <age id="13">40</age>
         </person>
    </book>I want to get the id value of name. using xpath-->//book[0]/person[0]/last[0]/name[0]/[@id]..is this a valid xpath to get the id's value? my java code as follows:
    import java.io.File;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Stack;
    import javax.xml.parsers.*;
    import javax.xml.xpath.*;
    import org.w3c.dom.Document;
    import org.xml.sax.*;
    import org.xml.sax.helpers.DefaultHandler;
    public class Evaluate {
         public static void main(String[] args) {
              String xp = "//book[0]/person[0]/last[0]/name[0]"+"/[@id]";
              String id="";
          try{
               // parse the XML as a W3C Document
              DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();// Create the parser
            Document doc = docBuilder.parse(new File("book.xml"));
             XPath xpath = XPathFactory.newInstance().newXPath();
             doc.getDocumentElement().normalize();
             XPathExpression xPathExpression = xpath.compile(xp);//-->getting error here
             id=xPathExpression.evaluate(xp).toString();
             id=xPathExpression.evaluate("person");
             System.out.println("id=" +id);
                  System.out.println("xp=" +xp);
                  }catch(Exception err){
                    System.out.println("Errpr= "+ err);
    can anyone please help me ?

    No, I believe that XPath indexes begin with 1, not with zero.

  • Extract Node Values using XPATH

    This may be a repeat question.
    No offence meant
    I am using XPATH to extract values from the nodes.
    I need to extract the value of i:RequestedBy Node using XPATH
    <?xml version="1.0" encoding="UTF-8"?>
    <i:Interest>
    <i:Status>0</i:Status>
    <i:Generation>2</i:Generation>
    <i:Details xsi:type="i:vanilla.details.stock">
       <i:RequestedBy>AA.MM</i:RequestedBy>
    The above XML is of type Document
    Document msgDoc;
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr;
    Object result=null;
         try {
                  expr = xpath.compile("i:Interest/i:Details/i:RequestedBy/text()");
                  result = expr.evaluate(msgDoc, XPathConstants.NODESET);
               NodeList nodes = (NodeList) result;
                for (int i = 0; i < nodes.getLength(); i++) {
                 System.out.println(nodes.item(i).getNodeValue());
         } catch (XPathExpressionException e1) {
         e1.printStackTrace();
                             I am getting null/
    Is my XPATH correct?

    I don't know if your XPath is correct or not. Your XML is not well-formed because the namespace declarations are missing. And I don't see where you set the namespace context for your XPath object; that is quite likely why it doesn't do what you want.

  • Set XML attribute from SetValue using Xpath

    Is there a trick to assigning a value to an attribute of an element in an XML variable using XPATH inside a setValue activity?  When I try something like
    Location
    /process_var/xml_var/test/@ID
    Expression:
    /process_var/test_value
    it complains about the @ sign in the location assignment.  I seem to be able to retrieve attributes just fine.

    Still having this issue.
    If I have an XML process variable which currently contains
    <Document>
        <Title />
        <Author />
        <Date />
    </Document>
    Try this, it fails.
    Location: /process_data/xml/Document/@ID
    Expression: 54
    Try this, it works.
    Location: /process_data/xml/Document/ID
    Expression: 54
    Now, alter the XML by adding an ID attribute
    <Document ID="">
        <Title />
        <Author />
        <Date />
    </Document>
    Try this, it works, where it failed earlier.
    Location: /process_data/xml/Document/@ID
    Expression: 54
    It appears to me, you can ADD a new node, but you can't ADD an attribute

  • Selcect/ update attribute value using xpath navigator/ linq to xml

    Hi Folks,
    below is my xml string and the highlighted bold attribute value needs to update. Since this element contains prefix im not able to select teh particular element. if i remove the prefixx im able to select but i need to keep prefix.
        <IOP:MtvnSvcReq xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:IOP="mtvnCWExternInteropReq" xmlns:IOP1="mtvnExtInteropReqData" xmlns:PR1="mtvnPRInteropReqData">
                              <IOP:Svc>
                                                 <IOP1:PR1>
                                                       <PR1:PRExternSSOReqData>
    <PR1:UserId>abcd</PR1:UserId>
                                                       </PR1:PRExternSSOReqData>
                                                 </IOP1:PR1>
                                </IOP:Svc>
                        </IOP:MtvnSvcReq>
    Thanks 

    Hi Pulikk,
    Do you mean you want  to change the attribute value(abcd)? If so,
    Please try the following code, i tested on my side, it changed successfully.
    //Here is the variable with which you assign a new value
    string newValue = string.Empty;
    XDocument objDoc = XDocument.Load(@"yourdata.xml");
    XNamespace IOP = "mtvnCWExternInteropReq";
    XNamespace IOP1 = "mtvnExtInteropReqData";
    XNamespace PR1 = "mtvnPRInteropReqData";
    foreach (var node in objDoc.Descendants(PR1 + "UserId"))
    node.Value = newValue;
    objDoc.Save(@"yourdata.xml");
    Have a nice day!
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Accessing documents in xml db in browser using xpath not returning results

    I have loaded the purchaseorder documents and schema (from Oracle Magazine article (Mar/Apr 2003) "From XML to Storage and Back" article.
    I am able to access the LineItems element of the purchaseorder document using:
    http://localhost:8080/oradb/SCOTT/PURCHASEORDER/ROW/PurchaseOrder[Reference="ADAMS-20011127121040988PST"]/LineItems
    However, I cannot access the indivicual LineItem elements using the ItemNumber attribute:
    http://localhost:8080/oradb/SCOTT/PURCHASEORDER/ROW/PurchaseOrder[Reference="ADAMS-20011127121040988PST"]/LineItems/LineItem[@ItemNumber="2"]
    I get the following result:
    <?xml version="1.0"?>
    <ERROR>ORA-00904::invalid identifier</ERROR>
    I need to be able to use this and other xpath statements to extract elements from my document. Any suggestions?

    I'm including a sample purchase order:
    <?xml version="1.0" ?>
    - <PurchaseOrder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://lisdev4db:8080/home/SCOTT/xsd/purchaseOrder.xsd">
    <Reference>WARD-20011127121040947PST</Reference>
    - <Actions>
    - <Action>
    <User>BLAKE</User>
    </Action>
    </Actions>
    <Reject />
    <Requestor>Stephen B. Ward</Requestor>
    <User>WARD</User>
    <CostCenter>S30</CostCenter>
    - <ShippingInstructions>
    <name>Stephen B. Ward</name>
    <address>1200 East Forty Seventh Avenue New York NY 10024 USA</address>
    <telephone>212 555 1212</telephone>
    </ShippingInstructions>
    <SpecialInstructions>Ground</SpecialInstructions>
    - <LineItems>
    - <LineItem ItemNumber="1">
    <Description>I Know Where I'm Going</Description>
    <Part Id="037429154427" UnitPrice="39.95" Quantity="2" />
    </LineItem>
    - <LineItem ItemNumber="2">
    <Description>The Last Wave</Description>
    <Part Id="037429161920" UnitPrice="29.95" Quantity="4" />
    </LineItem>
    - <LineItem ItemNumber="3">
    <Description>The Seven Samurai</Description>
    <Part Id="037429121726" UnitPrice="39.95" Quantity="2" />
    </LineItem>
    - <LineItem ItemNumber="4">
    <Description>Unbearable Lightness Of Being</Description>
    <Part Id="037429140222" UnitPrice="29.95" Quantity="4" />
    </LineItem>
    - <LineItem ItemNumber="5">
    <Description>Summertime</Description>
    <Part Id="037429130728" UnitPrice="29.95" Quantity="4" />
    </LineItem>
    - <LineItem ItemNumber="6">
    <Description>The Naked Kiss</Description>
    <Part Id="037429125823" UnitPrice="39.95" Quantity="4" />
    </LineItem>
    - <LineItem ItemNumber="7">
    <Description>Chihuly Over Venice</Description>
    <Part Id="037429141229" UnitPrice="29.95" Quantity="3" />
    </LineItem>
    - <LineItem ItemNumber="8">
    <Description>Written on the Wind</Description>
    <Part Id="715515011525" UnitPrice="29.95" Quantity="4" />
    </LineItem>
    - <LineItem ItemNumber="9">
    <Description>High and Low</Description>
    <Part Id="037429130322" UnitPrice="39.95" Quantity="2" />
    </LineItem>
    - <LineItem ItemNumber="10">
    <Description>Brief Encounter</Description>
    <Part Id="037429150726" UnitPrice="39.95" Quantity="2" />
    </LineItem>
    - <LineItem ItemNumber="11">
    <Description>Kwaidan</Description>
    <Part Id="037429152027" UnitPrice="29.95" Quantity="4" />
    </LineItem>
    - <LineItem ItemNumber="12">
    <Description>Withnail & I</Description>
    <Part Id="715515012225" UnitPrice="29.95" Quantity="1" />
    </LineItem>
    - <LineItem ItemNumber="13">
    <Description>Branded to Kill</Description>
    <Part Id="037429136225" UnitPrice="29.95" Quantity="2" />
    </LineItem>
    - <LineItem ItemNumber="14">
    <Description>The Hidden Fortress</Description>
    <Part Id="037429135129" UnitPrice="29.95" Quantity="2" />
    </LineItem>
    - <LineItem ItemNumber="15">
    <Description>The Most Dangerous Game</Description>
    <Part Id="037429137321" UnitPrice="24.95" Quantity="3" />
    </LineItem>
    - <LineItem ItemNumber="16">
    <Description>All That Heaven Allows</Description>
    <Part Id="715515011426" UnitPrice="39.95" Quantity="2" />
    </LineItem>
    - <LineItem ItemNumber="17">
    <Description>The Third Man</Description>
    <Part Id="037429141625" UnitPrice="39.95" Quantity="3" />
    </LineItem>
    - <LineItem ItemNumber="18">
    <Description>For All Mankind</Description>
    <Part Id="037429139523" UnitPrice="39.95" Quantity="3" />
    </LineItem>
    - <LineItem ItemNumber="19">
    <Description>Charade</Description>
    <Part Id="037429139424" UnitPrice="39.95" Quantity="2" />
    </LineItem>
    - <LineItem ItemNumber="20">
    <Description>Picnic at Hanging Rock</Description>
    <Part Id="037429126325" UnitPrice="29.95" Quantity="3" />
    </LineItem>
    - <LineItem ItemNumber="21">
    <Description>Christmas Glory From Westminster: An Evening of Christmas Music, Readings and Poetry</Description>
    <Part Id="037429161326" UnitPrice="19.95" Quantity="1" />
    </LineItem>
    - <LineItem ItemNumber="22">
    <Description>Samurai Three: Duel at Ganryu Island</Description>
    <Part Id="037429125625" UnitPrice="29.95" Quantity="3" />
    </LineItem>
    - <LineItem ItemNumber="23">
    <Description>Nanook of the North</Description>
    <Part Id="715515009829" UnitPrice="29.95" Quantity="3" />
    </LineItem>
    - <LineItem ItemNumber="24">
    <Description>My Man Godfrey</Description>
    <Part Id="715515011921" UnitPrice="39.95" Quantity="2" />
    </LineItem>
    - <LineItem ItemNumber="25">
    <Description>Discreet Charm of Bourgeoisie</Description>
    <Part Id="037429154625" UnitPrice="39.95" Quantity="1" />
    </LineItem>
    - <LineItem ItemNumber="26">
    <Description>The Seventh Seal</Description>
    <Part Id="037429124529" UnitPrice="39.95" Quantity="1" />
    </LineItem>
    - <LineItem ItemNumber="27">
    <Description>The Blob</Description>
    <Part Id="715515011129" UnitPrice="39.95" Quantity="3" />
    </LineItem>
    </LineItems>
    </PurchaseOrder>

  • Convert XML Node to String using XSLT

    Hi,
    Perhaps this has been discussed before. But i am looking at creating a XSLT mapping to take the entire inbound message and put it into a single node of the target.
    Is there a way?
    Thanks in advance
    Regards
    Venkat

    Hi Shankar,
    I have a input XML <root><a></a></root>
    I have a target <tgt><b></b></tgt>
    I need to have the target xml as
    <tgt><b>&lessthansign;root&greaterthansign;&lessthansign;a&greaterthansign;&lessthansign;/a&greaterthansign;&lessthansign;/root&greaterthansign;</b></tgt>
    Using the XSLT that you mentioned
    I am getting the format
    <tgt><b><root><a></a></root></b></tgt>
    Now the consumer of this message expects the data in the first type of format
    That is where i am getting stuck
    Thanks and Regards
    Venkat

  • Parse xml for newline chars using xpath

    Hi guys,
    need your help.
    I was curious to how can we use subString-before and subString after function to extracts records based on newline.
    Ex.
    for an strin xml field with data
    1st line
    2nd line
    and want to extract each line as separate record.
    Hope i am clear on req.
    anybody done something similar before?
    Thanks in advance.

    While SOA is based on handling XML messages, it has no relation with a presentation layer. Characters such as new-line, line-feed are processed as whitespace.
    If you want to add specific characters, you must encode this. So a new line would be &#10; This also applies for characters like quote and less-then and greater then.
    You must encode your information into UTF8 format.
    Marc
    http://orasoa.blogspot.com

  • Using XPATH to extract value.

    I need some help to extract the LatestFillQuantity element value using XPATH.
    in Java.
    I am unable to extract the value of 10000.
    Please help as to what have I done wrong.?
    The Document configNode contains the flwg:
    <?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
    <i:Interest >
         <i:Generation>3</i:Generation>
         <i:Extension>
            <i:Active.From/>
            <i:Order>
              <i:Status>Confirm</i:Status>
              <i:LatestFillQuantity>100</i:LatestFillQuantity>
            </i:Order>
    </i:Extension>
    </i:Interest>
    My Java Code
    private void extractValue(Document configNode)
         XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
              try{
             XPathExpression expr
              = xpath.compile("//i:Order/i:LatestFillQuantity/text()");
             Object result = expr.evaluate(configNode, XPathConstants.NODESET);
             NodeList nodes = (NodeList) result;
             for (int i = 0; i < nodes.getLength(); i++) {
                 System.out.println(nodes.item(i).getNodeValue());
             }catch(Exception e){
                  System.out.println("Sorry,this aint working");
         }

    The nodes being parsed are namespace prefixed.
    To parse a namespace node with the JDK 5.0 javax.xml.xpath package, set the NamespaceContext on the XPath object.
    An implementation of NamespaceContext with a single prefix corresponding to a namespace uri:
    public class NamespaceContextImpl implements NamespaceContext{
    public String uri;
    public String prefix;
    public NamespaceContextImpl(){}
    public NamespaceContextImpl(String prefix, String uri){
         this.uri=uri;
         this.prefix=prefix;
    public String getNamespaceURI(String prefix){
       return uri;
    public void setNamespaceURI(String uri){
       this.uri=uri;
    public String getPrefix(String uri){
       return prefix;
    public void setPrefix(String prefix){
       this.prefix=prefix;
    public Iterator getPrefixes(String uri){return null;}
    }

  • Using XPath for DOM traversal

    This question falls into the category of 'I know it's possible, I just need to find the idom in Java'.
    I'm coming from a MSFT world were the DOM-centric model of XML processing makes heavy use of XPATH for node selection. Basically using the method element.selectNodes(XPathExpresson) allows one to quickly extract the relevant subset of the parsed tree in the DOM as a nodeList. I've become accustomed to using XML for all strucutured storage that doesn't require a full database.
    The W3C DOM Level 3 spec supports evaluateExpression() for this purpose, but I can't believe that Java developers are still using tree traversal waiting for the spec to be implemented. I suppose that I could use getNodesByTagName(), but this is a chainsaw, and I need a scalpel. Anyway, I'm trying to figure out how, exactly, this gets done in Java.
    I figure the following are possibilities:
    1) It's in JAXP and I missed it
    2) One or more of the XML parsers supports XPATH as an extention
    3) There's a common package that sits on top of the DOM Document.
    4) There's a standard way to apply and XSLT methods to the DOM document
    5) Something I've never thought of.
    This is a generalized problem for me, so I can't rely on object serialization, Java-XML data mapping, etc. Any guidance would be greatly appreciated.

    I've written a Config file reader for XML in java,
    and it extracts values using XPath. This is
    some of the code you'll need:
    imports:
    import javax.xml.transform.TransformerException;
    import org.w3c.dom.*;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.apache.xerces.parsers.DOMParser;
    import org.apache.xpath.XPathAPI;
    import org.apache.xpath.objects.*;
    Document doc=....;
    * returns a single DOM Node from the config file.
    public Node getNode(String xpath) throws ConfigException {
    try {
    return XPathAPI.selectSingleNode(doc, xpath);
    } catch (TransformerException e) {
    throw new ConfigException("Can't find '"+xpath+"' ("+e.getMessage()+")");

  • How to extract node value by using xpath in orchestration shape

    i want extract the node value by using xpath in expression shape in orch, then assign to variable.
    then decide shape in if branch im using check condition based nodevalue .
    str = xpath(Message_3, ("string(/*[local-name()='Root' and namespace-uri()='http://BizTalk_Server_ProjectRNd2.Schema3']/*[local-name()='no' and namespace-uri()=''])"));
    but i got below error:
    xlang/s engine event log entry: Uncaught exception (see the 'inner exception' below) has suspended an instance of service 'BizTalk_Server_ProjectRNd2.BizTalk_Orchestration1(f3c581d3-049f-8a8a-9316-fc1235b03f99)'.
    The service instance will remain suspended until administratively resumed or terminated. 
    If resumed the instance will continue from its last persisted state and may re-throw the same unexpected exception.
    InstanceId: 020779be-713d-408c-9ff4-fd1462c2e52c
    Shape name: Expression_1
    ShapeId: b865a3e1-7ebe-410d-9f60-8ad2139ad234
    Exception thrown from: segment 1, progress 10
    Inner exception: There is an error in the XML document.
    Exception type: InvalidOperationException
    Source: System.Xml
    Target Site: System.Object Deserialize(System.Xml.XmlReader, System.String, System.Xml.Serialization.XmlDeserializationEvents)
    The following is a stack trace that identifies the location where the exception occured
       at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
       at Microsoft.XLANGs.Core.Part.XPathLoad(Part sourcePart, String xpath, Type dstType)
       at BizTalk_Server_ProjectRNd2.BizTalk_Orchestration1.segment1(StopConditions stopOn)
       at Microsoft.XLANGs.Core.SegmentScheduler.RunASegment(Segment s, StopConditions stopCond, Exception& exp)
    Additional error information:
            <no xmlns=''> was not expected.
    Exception type: InvalidOperationException
    Source: System.Xml
    Target Site: System.Object Read_string()
    The following is a stack trace that identifies the location where the exception occured
       at System.Xml.Serialization.XmlSerializationPrimitiveReader.Read_string()
       at System.Xml.Serialization.XmlSerializer.DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events)
       at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)

    Hi,
    as per your  code i got below error 
    Uncaught exception (see the 'inner exception' below) has suspended an instance of service 'BizTalk_Server_ProjectRNd2.BizTalk_Orchestration1(f3c581d3-049f-8a8a-9316-fc1235b03f99)'.
    The service instance will remain suspended until administratively resumed or terminated. 
    If resumed the instance will continue from its last persisted state and may re-throw the same unexpected exception.
    InstanceId: f5fffb05-e6d6-4765-83da-4e6c9696dd8a
    Shape name: Expression_1
    ShapeId: b865a3e1-7ebe-410d-9f60-8ad2139ad234
    Exception thrown from: segment 1, progress 10
    Inner exception: There is an error in the XML document.
    Exception type: InvalidOperationException
    Source: System.Xml
    Target Site: System.Object Deserialize(System.Xml.XmlReader, System.String, System.Xml.Serialization.XmlDeserializationEvents)
    The following is a stack trace that identifies the location where the exception occured
       at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializat
    this is my schema:
      <?xml version="1.0" encoding="utf-16"
    ?>
    <xs:schema xmlns="http://BizTalk_Server_ProjectRNd2.Schema3" xmlns:b="http://schemas.microsoft.com/BizTalk/2003"
    xmlns:ns0="https://BizTalk_Server_ProjectRNd2.PropertySchema" targetNamespace="http://BizTalk_Server_ProjectRNd2.Schema3" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:annotation>
    <xs:appinfo>
    <b:imports>
      <b:namespace
    prefix="ns0" uri="https://BizTalk_Server_ProjectRNd2.PropertySchema" location=".\PropertySchema.xsd"
    />
      </b:imports>
      </xs:appinfo>
      </xs:annotation>
    <xs:element name="Root">
    <xs:annotation>
    <xs:appinfo>
    <b:properties>
      <b:property
    name="ns0:no" xpath="/*[local-name()='Root' and namespace-uri()='http://BizTalk_Server_ProjectRNd2.Schema3']/*[local-name()='no' and namespace-uri()='']"
    />
      </b:properties>
      </xs:appinfo>
      </xs:annotation>
    <xs:complexType>
    <xs:sequence>
      <xs:element
    name="no" type="xs:string" />
      <xs:element
    name="name" type="xs:string" />
      </xs:sequence>
      </xs:complexType>
      </xs:element>
      </xs:schema>

  • SSMS 2012:FOR XML PATH Using XPath Node Tests-Columnn name 'test()' contains an invalid XML identifier as required by FOR XML?

    Hi all,
    I am learning XPATH and XQUERY from the Book "Pro T-SQL 2008 Programmer's Guide" written by Michael Coles, (published by apress). I copied the Code Listing 12-8 FOR XML PATH Using XPath Node Tests (listed below) and executed it in my
    SQL Server 2012 Management Studio:
    --Coles12_8.sql // saved in C:/Documemnts/SQL Server Management Studio
    -- Coles Listing 12-8 FOR XML PATH Using XPATH Node Tests
    -- Retrieving Name and E-mail Addresses with FOR XML PATH in AdvantureWorks
    -- 16 March 2015 0935 AM
    USE AdventureWorks;
    GO
    SELECT
    p.NameStyle AS "processing-instruction(nameStyle)",
    p.BusinessEntityID AS "Person/@ID",
    p.ModifiedDate AS "comment()",
    pp.PhoneNumber AS "test()",
    FirstName AS "Person/Name/First",
    MiddleName AS "Person/Name/Middle",
    LastName AS "Person/Name/Last",
    EmailAddress AS "Person/Email"
    FROM Person.Person p
    INNER JOIN Person.EmailAddress e
    ON p.BusinessEntityID = e.BusinessEntityID
    INNER JOIN Person.PersonPhone pp
    ON p.BusinessEntityID = pp.BusinessEntityID
    FOR XML PATH;
    I got the following error message:
    Msg 6850, Level 16, State 1, Line 2
    Column name 'test()' contains an invalid XML identifier as required by FOR XML; '('(0x0028) is the first character at fault.
    I have no ideas why I got this error message.  Please kindly help and advise me how to resolve this error.
    Thanks in advance,  Scott Chang

    Hi Michelle, Thanks for your nice response.
    I corrected the mistake and executed the revised code. It worked nicely.
    I just have one question to ask you about the appearance of the xml output of my Co;les12_8.sql:
    <row>
    <?nameStyle 0?>
    <Person ID="1" />
    <!--2003-02-08T00:00:00-->697-555-0142<Person><Name><First>Ken</First><Middle>J</Middle><Last>Sánchez</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="2" />
    <!--2002-02-24T00:00:00-->819-555-0175<Person><Name><First>Terri</First><Middle>Lee</Middle><Last>Duffy</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="3" />
    <!--2001-12-05T00:00:00-->212-555-0187<Person><Name><First>Roberto</First><Last>Tamburello</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="4" />
    <!--2001-12-29T00:00:00-->612-555-0100<Person><Name><First>Rob</First><Last>Walters</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="5" />
    <!--2002-01-30T00:00:00-->849-555-0139<Person><Name><First>Gail</First><Middle>A</Middle><Last>Erickson</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="6" />
    <!--2002-02-17T00:00:00-->122-555-0189<Person><Name><First>Jossef</First><Middle>H</Middle><Last>Goldberg</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="7" />
    <!--2003-03-05T00:00:00-->181-555-0156<Person><Name><First>Dylan</First><Middle>A</Middle><Last>Miller</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="8" />
    <!--2003-01-23T00:00:00-->815-555-0138<Person><Name><First>Diane</First><Middle>L</Middle><Last>Margheim</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="9" />
    <!--2003-02-10T00:00:00-->185-555-0186<Person><Name><First>Gigi</First><Middle>N</Middle><Last>Matthew</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="10" />
    <!--2003-05-28T00:00:00-->330-555-2568<Person><Name><First>Michael</First><Last>Raheem</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    <?nameStyle 0?>
    <Person ID="11" />
    <!--2004-12-29T00:00:00-->719-555-0181<Person><Name><First>Ovidiu</First><Middle>V</Middle><Last>Cracium</Last></Name><Email>[email protected]</Email></Person></row>
    <row>
    I feel this xml output is not like the regular xml output.  Do you know why it is diffrent from the regular xml xml output?  Please comment on this matter.
    Thanks,
    Scott Chang
    What do you mean by regular xml document? Are you referring to fact that its missing a root element? if yes it can be added as below
    USE AdventureWorks;
    GO
    SELECT
    p.NameStyle AS "processing-instruction(nameStyle)",
    p.BusinessEntityID AS "Person/@ID",
    p.ModifiedDate AS "comment()",
    pp.PhoneNumber AS "text()",
    FirstName AS "Person/Name/First",
    MiddleName AS "Person/Name/Middle",
    LastName AS "Person/Name/Last",
    EmailAddress AS "Person/Email"
    FROM Person.Person p
    INNER JOIN Person.EmailAddress e
    ON p.BusinessEntityID = e.BusinessEntityID
    INNER JOIN Person.PersonPhone pp
    ON p.BusinessEntityID = pp.BusinessEntityID
    FOR XML PATH('ElementName'),ROOT('RootName');
    replace ElementName and RootName with whatever name you need to set for element as well as the root element
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Failing to extract xml value using Jdom & Xpath

    I have a method (getSingleNodeValue()) which when passed an xpatch expression will extract the value of the specified element in the xml document refered to in 'doc'. Assume doc at this point has been initialised as shown below and xmlInput is the buffer containing the xml content.
        SAXBuilder     builder          =     null;
        Document     doc          =     null;
        XPath          xpathInstance     =      null;
        doc     = builder.build(new StringReader(xmlInput));When i call the method, i pass the following xpath xpression
        /TOP4A/PERLODSUMDEC/TINPLD1/text()Here is the method. It basically just takes an xml buffer and uses xpath to extract the value:
        public static String getSingleNodeValue(String xpathExpr) throws Exception{
             Text list = null;
             try {
                  xpathInstance = XPath.newInstance(xpathExpr);
                  list = (Text) xpathInstance.selectSingleNode(doc);
             } catch (JDOMException e) {
                  throw new Exception(e);
             }catch (Exception e){
                  throw new Exception(e);
             return list==null ? "?" : list.getText();
        }The above method always returns "?" i.e. nothing is found so 'list' is null.
    The xml document it looks at is
        <TOP4A xmlns="http://www.testurl.co.uk/enment/gqr/3232/1">   
          <HEAD>
            <Doc>ABCDUK1234</Doc> 
          </HEAD>   
          <PERLODSUMDEC>
            <TINPLD1>10109000000000000</TINPLD1>
          </PERLODSUMDEC>
        </TOP4A>The same method works with other xml documents so i am not sure what is special about this one. There is no exception so the xml is valid xml. Its just that the method always sets 'list' to null. Any ideas?
    Edit
    Here is a running program testing the above:
        import org.jdom.*;
        import org.jdom.input.*;
        import org.jdom.xpath.*;
        import java.io.IOException;
        import java.io.StringReader;
        public class XpathTest {
             public static String getSingleNodeValue(String xpathExpr, String xmlInput) throws Exception{
                 Text list = null;
                  SAXBuilder  builder           =   null;
                  Document    doc                    =   null;
                  XPath       xpathInstance   =   null;
                 try {
                      builder     = new SAXBuilder();     
                      doc          = builder.build(new StringReader(xmlInput));
                     xpathInstance = XPath.newInstance(xpathExpr);
                     list = (Text) xpathInstance.selectSingleNode(doc);
                 } catch (JDOMException e) {
                     throw new Exception(e);
                 }catch (Exception e){
                     throw new Exception(e);
                 return list==null ? "Nothing Found" : list.getText();
             public static void main(String[] args){
                  String xmlInput1 = "<TOP4A xmlns=\"http://www.testurl.co.uk/enment/gqr/3232/1\"><HEAD><Doc>ABCDUK1234</Doc></HEAD><PERLODSUMDEC><TINPLD1>10109000000000000</TINPLD1></PERLODSUMDEC></TOP4A>";
                  String xpathExpr = "/TOP4A/PERLODSUMDEC/TINPLD1/text()";
                  XpathTest xp = new XpathTest();
                  try {
                       System.out.println(xp.getSingleNodeValue(xpathExpr, xmlInput1));
                  } catch (Exception e) {
                       // TODO Auto-generated catch block
                       e.printStackTrace();
        }When i run the above, the output is
        Nothing foundEdit
    I have run some further testing and it appears that if i remove the namespace url it does work. Not sure why yet. Is there any way i can tell it to ignore the namespace?
    Edited by: ziggy on Sep 3, 2011 4:57 PM

    ziggy wrote:
    <TOP4A xmlns="http://www.testurl.co.uk/enment/gqr/3232/1">   
    <HEAD>
    <Doc>ABCDUK1234</Doc> 
    </HEAD>   
    <PERLODSUMDEC>
    <TINPLD1>10109000000000000</TINPLD1>
    </PERLODSUMDEC>
    </TOP4A>
    It works fine, the problem is not with namespace, it is with url have given.
    Editing:
    Found a way to say the program to ignore namespace.
    You have to use Xpath.addNamespace(prefix,uri), and pass the prefix to your pattern string.
    If not clear refer the below code:
    import org.jdom.*;
        import org.jdom.input.*;
        import org.jdom.xpath.*;
        import java.io.IOException;
        import java.io.StringReader;
        public class XpathTest {
             public static String getSingleNodeValue(String xpathExpr, String xmlInput) throws Exception{
                 Text list = null;
                  SAXBuilder  builder           =   null;
                  Document    doc                    =   null;
                  XPath       xpathInstance   =   null;
                 try {
                      builder     = new SAXBuilder();     
                      doc          = builder.build(new StringReader(xmlInput));
                     xpathInstance = XPath.newInstance(xpathExpr);
                        xpathInstance.addNamespace("ns","http://www.testurl.co.uk/enment/gqr/3232/1");
                     list = (Text) xpathInstance.selectSingleNode(doc);
                 } catch (JDOMException e) {
                     throw new Exception(e);
                 }catch (Exception e){
                     throw new Exception(e);
                 return list==null ? "Nothing Found" : list.getText();
             public static void main(String[] args){
                  String xmlInput1 = "<TOP4A xmlns=\"http://www.testurl.co.uk/enment/gqr/3232/1\"><HEAD><Doc>ABCDUK1234</Doc></HEAD><PERLODSUMDEC><TINPLD1>10109000000000000</TINPLD1></PERLODSUMDEC></TOP4A>";
                  String xpathExpr = "/ns:TOP4A/ns:PERLODSUMDEC/ns:TINPLD1/text()";
                  XpathTest xp = new XpathTest();
                  try {
                       System.out.println(xp.getSingleNodeValue(xpathExpr, xmlInput1));
                  } catch (Exception e) {
                       // TODO Auto-generated catch block
                       e.printStackTrace();
        }Edited by: 833545 on Sep 8, 2011 11:35 PM

  • Using XSLT to extract value of a XML node with namespace

    I have a XML source code here.
    <?xml version="1.0" encoding="utf-8" ?>
    <rss version="2.0" xmlns:job="http://www.pageuppeople.com">
      <channel>
        <title>SMH Jobs</title>
        <link>internalrecruitment.smhgroup.com.au/jobsrss.ashx?stp=di</link>
        <description>A listing of jobs available here</description>
        <item>
          <title>eCommerce Optimisation Advisor</title>
          <description>A new and exciting opportunity exists for an experienced eCommerce Advisor to join</description>
          <job:location PUReferenceID="3711">Sydney - Inner Suburbs & CBD</job:location>
        </item>
      </channel>
    </rss>
    I want to use XSLT to extract value of a XML node with namespace <job:location>, and the returned value should be string 'Sydney - Inner Suburbs & CBD'. I tried a few XSL code below, but failed with error or nothing was returned.
    <xsl:value-of select="job:location" disable-output-escaping="yes"/>
    <xsl:value-of select="job/location" disable-output-escaping="yes"/>
    <xsl:value-of select="job\location" disable-output-escaping="yes"/>
    <xsl:value-of select="location" disable-output-escaping="yes"/>
    This might be an easy question for you, but I would appreciate if anyone can help.

    Hi Suncorp IT Learner,
    We need to tell the XSLT that some elements are in another namespace. Copy the xmls declarations for the prefixes you need to use. Then use the xsl format as:
    <xsl: value-of select=”job:location/@PUReferenceID”/>
    In following issue, Chriztian has a good explanation:
    http://our.umbraco.org/forum/developers/xslt/33353-XSLT-reading-XML-attribute-value
    Thanks,
    Qiao Wei
    TechNet Community Support

Maybe you are looking for

  • How to report stolen iMAC in the UK

    Hi My iMac just got stolen. How can I report it? Can I Block it ? or make it not be able to working again? Kind Regards, Banu

  • Error message when I connect to mail

    This Mac can't connect to iCloud because of a problem with "[email protected]". why do I get this message when I open Mail since I updated to Maverick I have tried all settings etc but it still comes up on mail start up.?

  • SAFARI CRASH.. QUIT UNEXPECTEDLY.. EXC BAD ACCESS

    hey guys.. noticed today that safari was crashing after viewing certain websites.. one was a blog and the other was a yahoo page.. it would quit.. and i would get the crash log.. but in some instances the program will crash and the screen will turn b

  • Attribute Value Length

    Hi, I tried to restrict length of attribute by using {6}. But some how it allow me to update value of attribute with 10 characters. Is their a way i can restrict ldap attribute value to fixed lenght. I i try to add more then defined length it will no

  • IPod nano and cases

    Hi, I'm looking at getting an iPod nano. It'll need a case since I'll be using my iPod alot in my pocket. I see that the nano comes with a case. Is this case worth anything? Or should I look at buying a third party case for it? The only thing I need