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
Similar Messages
-
Network LOD support for All Paths between 2 nodes
In the in-memory Network API, there is a method NetworkManager.allPaths. This method returns available paths between 2 nodes with possible constraints. I am looking for a similar method in the LOD NetworkAnalyst class and am not finding it. Is there something similar?
Or, here is what I want to do, and maybe there is a better way to do it. I am using NDM to data-mine our roadway inventory. Its a big network, whole state of Ohio, all roads--both local and state. One of the things I am trying to identify are what we call co-located routes. These are routes that have multiple names, for example, the ohio turnpike is both Interstate 80 and 90 on the same bed of road. In our line work, where these routes are co-located, we would only have a record for 80. The portion of 90 that we would have would be only in the case where it is NOT co-located with 80; in other words, 90 has a gap where it is co-located with 80. This is true for all our roads. In this case, we call 80 the primary, and 90 the secondary. We can have infinite secondaries (our worst case scenario is 6 routes overlapping). My situation in many cases, is I know that a route becomes secondary, I know how long the secondary section is, but I don't know what the primary is, so I want to discover it.
Given these assumptions, I should be able to ask for all paths between 2 nodes that exactly match a cost (the overall length of the overlap). This should be simple with NDM. I provide a begin node, an end node, and a target cost, possible some traversal constraints, and it returns me the candidate paths. I thought that NetworkAnalyst.withinCost would do this, but as I discovered from the Stored Procedure docs, it returns the shortest path within the given less than or equal to the given cost--not necessarily the path I am looking for.
Any advice? FYI, I am using Oracle 11GR2.
Thanks, TomSo what I have come up with so far, is that the NetworkAnalyst trace methods provide this type of functionality. For example, with traceOut, I provide a start node, distance and some traversal constraints, and it returns me all paths less than or equal to the specified distance. What was throwing me a little with this method was the application of the LODGoalNode. I was thinking that the goal node would allow me to specify a particular node to be a requirement for the entire path such that a resulting path would have my start node, and end on a particular goal node with links in between. That IS NOT how it works. The LODGoalNode.isGoal is tested for EACH link that is part of a potential path, and only if this method returns true, is it added to the resulting path list.
In my case, if I specified a start node and implemented the LODGoalNode.isGoal method such that it tested the provided end node for equality to my target node, the result would be that only links containing that specific goal node in the link. Anyway, so in my implementation, I leave the goalNode of the traceOut method null.
So I have a new question. Is there a way to test when a path has been found, and then apply some constraints on it (PathConstraint)? This would be useful in cases where you get many paths returned to you, but in addition to a maximum distance constraint, you also want to apply for example a minimum distance on the resulting path, or that this is only a valid path if it ends on a particular node. Maybe there is a way to do this, and I haven't figured it out yet. The old AnalysisInfo class used to have a way to query the current path links and nodes, that would be useful in the LODAnalysisInfo class to help accomplish this perhaps? This feature isn't critical, because I can filter the list of paths returned from traceOut on my own after they are returned, but it would add some efficiency, especially when a large amount of paths are returned.
Thanks, Tom -
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 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 -
Xml loading using xpath in pl/sql
Hi,
I am loading xml using xpath query bu i am stucked here.I am not able to pass the loop counter "I" into the query.Please help.
The problem is in line " 13 FROM xml_table,table(XMLSequence(extract(OBJECT_VALUE, '/BIF/SBI/SBC/flag'))) li;
" in the below block
1 declare
2 SBI_count pls_integer;
3 begin
4 select count(*)
5 into SBI_count
6 from xml_table,table(XMLSequence(extract(OBJECT_VALUE, '/BIF/SBI') ) );
7 dbms_output.put_line( 'SBI_count '||SBI_count );
8 for I in 1..SBI_count
9 LOOP
10 INSERT INTO Subclass_Date_Flags( Subclass_Id,
11 subclass_date_flags_8 )
12 SELECT 'SID',extractvalue(VALUE(li), '//flag')
13 FROM xml_table,table(XMLSequence(extract(OBJECT_VALUE, '/BIF/SBI[I]/SBC/flag'))) li;
14 dbms_output.put_line( 'Row '||SQL%ROWCOUNT );
15 END LOOP;
16 commit;
17* end;
SQL> /
SBI_count 2
Row 0
Row 0
PL/SQL procedure successfully completed.Try this code, just keep a reference to your root node so you can keep appending children to it:
DECLARE
xmlDoc xmldom.DOMDocument;
xmlNode xmldom.DOMNode;
xmlNode1 xmldom.DOMNode;
xmlElem1 xmldom.DOMElement;
xmlElem2 xmldom.DOMElement;
xmlText xmldom.DOMText;
CURSOR cur_emp IS
SELECT *
FROM emp;
--WHERE empno = 7369;
row_emp emp%ROWTYPE;
BEGIN
xmlDoc := xmldom.newDOMDocument;
xmlNode := xmldom.makeNode(xmlDoc);
xmlElem1 := xmldom.createElement(xmlDoc,'root');
xmlNode := xmldom.appendChild(xmlNode,xmldom.makeNode(xmlElem1));
OPEN cur_emp;
LOOP
FETCH cur_emp INTO row_emp;
EXIT WHEN cur_emp%NOTFOUND;
xmlElem2 := xmldom.createElement(xmlDoc,'name');
xmldom.setAttribute(xmlElem2, 'empno',TO_CHAR(row_emp.empno));
xmlNode1 := xmldom.appendChild(xmlNode,xmldom.makeNode(xmlElem2));
xmlText := xmldom.createTextNode(xmlDoc,row_emp.ename);
xmlNode1 := xmldom.appendChild(xmlNode1,xmldom.makeNode(xmlText));
END LOOP;
CLOSE cur_emp;
xmldom.writeToFile(xmlDoc,'c:\xmltest1.txt');
END;
null -
Parsing an xml document using XPATH
Hello,
I am pretty new to programming "Java and XML" and right now very confused with the range of available xml parsers,xpath engines and xslt processors.I need some guidance on how to parse a xpath expression with variables in it .
Thanks,
Chan.Gregory . Thank you so much for the insight into parsing and xpath expression evalaution . I downloaded the XpathExamples.java file , practical xml jar file and executed the program to see the output for various example functions that you have created .All of them worked perfectly without any issues.
In the variablesExample() function , I added the following lines to check if it works :
variables.put(new QName("myvar"), "foo");
System.out.println("myvar bound as 'argle' = " + xpath.evaluate("/$foo/bar/baz", dom));
I ran into exceptions like ..
Exception in thread "main" javax.xml.transform.TransformerException: Extra illegal tokens: '$', 'foo', '/', 'bar', '/', 'baz'
Can you please tell me what was I doing wrong ? I am also planning to use starts-with() function in xpath expression . Will it work ?
Thank you for your reasoning. -
Fitness for Shortest path using a genetic algorithm
Hi.
I have this problem:
I'm doing a program that has a map and two points. the map has wall that are not valid positions.
I have used a A* algorithm to calculate the shortest path and is working fine.
now i'm implementing a genetic algorithm to solve the problem but i'm not having sucess.
My genetic operator are directions (left, right, up and down).
I'm not being able to find a goodfitness function to solve the problem.
can someone tell me a god function or here I can found information about that?
I have been searching on google and I have not yet had sucess.
I have tryed two diferent fitness tecniques:
- add 1 for each step and if it finds a wall or gets out of the map add the maximum value (mapsize*mapsize).
- the other one is add the valid steps and if it finds a wall or gets out of the map add the number of necessary steps to gets to destination. the valid steps has a weight of 30% and the necessary steps has a weight of 70% (i have tryed to use diferent weight).
Can someone help me?
thanksHow about adapting your TSP code as follows. Your graph G(V, E) has two special vertices: v_s and v_d (start and destination). Let a candidate solution consist of a permutation of V\{v_s, v_d}u{v_m} where v_m is a new marker vertex whose purpose is to allow you to treat part of the candidate solution as irrelevant. Given candidate solution v_0 v_1 v_2 ... v_n v_m v_n+1 ... the weight is c(v_s, v_0) + c(v_0, v_1) + ... + c(v_n-1, v_n) where c(v_a, v_b) is the cost of the edge ab.
-
Generate xml using FOR XML PATH from table with hierarchy
I need to create xml from a table like:
EL1 EL2 EL3 Attr01 Attr02 Attr03 Attr04
E10, , ,a,b,c,d
E10,E1010, ,a,b,c,d
E10,E1010,E101010,a,b,c,d
E10,E1010,E101020,a,b,c,d
E10,E1010,E101030,a,b,c,d
E10,E1020, ,a,b,c,d
E10,E1020,E102010,a,b,c,d
E20, , ,a,b,c,d
E20,E2010, ,a,b,c,d
E20,E2010,E201010,a,b,c,d
E20,E2020, ,a,b,c,d
E20,E2020,E202010,a,b,c,d
E20,E2020,E202020,a,b,c,d
The hierarchy is EL1--EL2--EL3, and the 3 columns should be elements of xml;
The other for columns Attr01,Attr02,Attr03,Attr04 should be attributes of xml;
The actual table could have more than 500 rows(there are many values for El1,EL2,and EL3).
The expected xml should like:
<root>
<E10 Attr01="a" Attr02="b" Attr03="c" Attr04="d">
<E1010 Attr01="a" Attr02="b" Attr03="c" Attr04="d">
<E101010 Attr01="a" Attr02="b" Attr03="c" Attr04="d" />
<E101020 Attr01="a" Attr02="b" Attr03="c" Attr04="d" />
<E101030 Attr01="a" Attr02="b" Attr03="c" Attr04="d" />
</E1010>
<E1020 Attr01="a" Attr02="b" Attr03="c" Attr04="d">
<E102010 Attr01="a" Attr02="b" Attr03="c" Attr04="d" />
</E1020>
</E10>
<E20 Attr01="a" Attr02="b" Attr03="c" Attr04="d">
<E2010 Attr01="a" Attr02="b" Attr03="c" Attr04="d">
<E201010 Attr01="a" Attr02="b" Attr03="c" Attr04="d" />
</E2010>
<E2020 Attr01="a" Attr02="b" Attr03="c" Attr04="d">
<E202010 Attr01="a" Attr02="b" Attr03="c" Attr04="d" />
<E202020 Attr01="a" Attr02="b" Attr03="c" Attr04="d" />
</E2020>
</E20>
</root>
I create a sample Src table:
CREATE TABLE Src
EL1 VARCHAR(10),
EL2 VARCHAR(10),
EL3 VARCHAR(10),
Attr01 VARCHAR(10),
Attr02 VARCHAR(10),
Attr03 VARCHAR(10),
Attr04 VARCHAR(10)
GO
INSERT INTO Src
(EL1,EL2,EL3,Attr01,Attr02,Attr03,Attr04
SELECT 'E10','','','a','b','c','d'
UNION SELECT 'E10','E1010','','a','b','c','d'
UNION SELECT 'E10','E1010','E101010','a','b','c','d'
UNION SELECT 'E10','E1010','E101020','a','b','c','d'
UNION SELECT 'E10','E1010','E101030','a','b','c','d'
UNION SELECT 'E10','E1020','','a','b','c','d'
UNION SELECT 'E10','E1020','E102010','a','b','c','d'
UNION SELECT 'E20','','','a','b','c','d'
UNION SELECT 'E20','E2010','','a','b','c','d'
UNION SELECT 'E20','E2010','E201010','a','b','c','d'
UNION SELECT 'E20','E2020','','a','b','c','d'
UNION SELECT 'E20','E2020','E202010','a','b','c','d'
UNION SELECT 'E20','E2020','E202020','a','b','c','d'
GO
I tried to use FOR XML PATH to generate xml for the sample data. When the records increase to a few hundreds, it's not a good idea.
Here is my script:
SELECT
(SELECT Attr01 AS '@Attr01'
,Attr02 AS '@Attr02'
,Attr03 AS '@Attr03'
,Attr04 AS '@Attr04'
,( SELECT
Attr01 AS '@Attr01'
,Attr02 AS '@Attr02'
,Attr03 AS '@Attr03'
,Attr04 AS '@Attr04'
,( SELECT
Attr01 AS '@Attr01'
,Attr02 AS '@Attr02'
,Attr03 AS '@Attr03'
,Attr04 AS '@Attr04'
FROM Src
WHERE EL3 = 'E101010'
FOR XML PATH('E101010'),TYPE
) AS 'node()'
,( SELECT
Attr01 AS '@Attr01'
,Attr02 AS '@Attr02'
,Attr03 AS '@Attr03'
,Attr04 AS '@Attr04'
FROM Src
WHERE EL3 = 'E101020'
FOR XML PATH('E101020'),TYPE
) AS 'node()'
,( SELECT
Attr01 AS '@Attr01'
,Attr02 AS '@Attr02'
,Attr03 AS '@Attr03'
,Attr04 AS '@Attr04'
FROM Src
WHERE EL3 = 'E101030'
FOR XML PATH('E101030'),TYPE
) AS 'node()'
FROM Src
WHERE EL2 = 'E1010' AND (EL1 <>'' AND EL3 ='')
FOR XML PATH('E1010'),TYPE
) AS 'node()'--1010
,( SELECT
Attr01 AS '@Attr01'
,Attr02 AS '@Attr02'
,Attr03 AS '@Attr03'
,Attr04 AS '@Attr04'
,( SELECT
Attr01 AS '@Attr01'
,Attr02 AS '@Attr02'
,Attr03 AS '@Attr03'
,Attr04 AS '@Attr04'
FROM Src
WHERE EL3 = 'E102010'
FOR XML PATH('E102010'),TYPE
) AS 'node()'
FROM Src
WHERE EL2 = 'E1020' AND (EL1 <>'' AND EL3 ='')
FOR XML PATH('E1020'),TYPE
) AS 'node()'--1020
FROM Src
WHERE EL1 = 'E10' AND (EL2 ='' AND EL3 ='')
FOR XML PATH('E10'),TYPE) 'node()'
,(SELECT Attr01 AS '@Attr01'
,Attr02 AS '@Attr02'
,Attr03 AS '@Attr03'
,Attr04 AS '@Attr04'
,( SELECT
Attr01 AS '@Attr01'
,Attr02 AS '@Attr02'
,Attr03 AS '@Attr03'
,Attr04 AS '@Attr04'
,( SELECT
Attr01 AS '@Attr01'
,Attr02 AS '@Attr02'
,Attr03 AS '@Attr03'
,Attr04 AS '@Attr04'
FROM Src
WHERE EL3 = 'E201010'
FOR XML PATH('E201010'),TYPE
) AS 'node()'
FROM Src
WHERE EL2 = 'E2010' AND (EL1 <>'' AND EL3 ='')
FOR XML PATH('E2010'),TYPE
) AS 'node()'--2010
,( SELECT
Attr01 AS '@Attr01'
,Attr02 AS '@Attr02'
,Attr03 AS '@Attr03'
,Attr04 AS '@Attr04'
,( SELECT
Attr01 AS '@Attr01'
,Attr02 AS '@Attr02'
,Attr03 AS '@Attr03'
,Attr04 AS '@Attr04'
FROM Src
WHERE EL3 = 'E202010'
FOR XML PATH('E202010'),TYPE
) AS 'node()'
,( SELECT
Attr01 AS '@Attr01'
,Attr02 AS '@Attr02'
,Attr03 AS '@Attr03'
,Attr04 AS '@Attr04'
FROM Src
WHERE EL3 = 'E202020'
FOR XML PATH('E202020'),TYPE
) AS 'node()'
FROM Src
WHERE EL2 = 'E2020' AND (EL1 <>'' AND EL3 ='')
FOR XML PATH('E2020'),TYPE
FROM Src
WHERE EL1 = 'E20' AND (EL2 ='' AND EL3 ='')
FOR XML PATH('E20'),TYPE) AS 'node()'
FOR XML PATH(''),ROOT('root')
If I get a few hundreds of rows, how huge the script should be. Does anyone have better solution for this? Thanks.
TaowBob,
Thanks! And sorry for late feedback.
The XSD requires the xml structures like the following
<Schools>
<School01>Some school</School01>
<School02>Some other school</School02>
</Schools>
I have to use the number in the element name.
Right now I just use the nested FOR XML PATH, although I have to write thousand lines code.
Thanks anyway.
Tao
Tao -
Hi all,
I used the following code to create a new Database (ScottChangDB) and a new Table (marvel) in my SQL Server 2012 Management Studio (SSMS2012) successfully:
-- ScottChangDB.sql saved in C://Documents/SQL Server XQuery_MacLochlainns Weblog_code
-- 14 April 2015 09:15 AM
USE master
IF EXISTS
(SELECT 1
FROM sys.databases
WHERE name = 'ScottChangDB')
DROP DATABASE ScottChangDB
GO
CREATE DATABASE ScottChangDB
GO
USE ScottChangDB
CREATE TABLE [dbo].[marvel] (
[avenger_name] [char] (30) NULL, [ID] INT NULL)
INSERT INTO marvel
(avenger_name,ID)
VALUES
('Hulk', 1),
('Iron Man', 2),
('Black Widow', 3),
('Thor', 4),
('Captain America', 5),
('Hawkeye', 6),
('Winter Soldier', 7),
('Iron Patriot', 8);
SELECT avenger_name FROM marvel ORDER BY ID For XML PATH('')
DECLARE @x XML
SELECT @x=(SELECT avenger_name FROM marvel ORDER BY ID FOR XML PATH('Marvel'))--,ROOT('root'))
SELECT
person.value('Marvel[4]', 'varchar(100)') AS NAME
FROM @x.nodes('.') AS Tbl(person)
ORDER BY NAME DESC
--Or if you want the completed element
SELECT @x.query('/Marvel[4]/avenger_name')
DROP TABLE [marvel]
Now I am trying to create my first XML Schema Collection to do the Validation on the Field Name (Column Title) of the "marvel" Table. I have studied Chapter 4 XML SCHEMA COLLECTIONS of the book "Pro SQL Server 2008 XML" written by
Michael Coles (published by Apress) and some beginning pages of XQuery Language Reference, SQL Server 2012 Books ONline (published by Microsoft). I mimicked Coles' Listing 04-05 and I wanted to execute the following first-drafted sql in
my SSMS2012:
-- Reference [Scott Chang modified Listing04-05.sql of Pro SQL Server 2008 XML by Michael Coles (Apress)]
-- [shcColes04-05.sql saved in C:\\Documents\XML_SQL_Server2008_code_Coles_Apress]
-- [executed: 2 April 2015 15:04 PM]
-- shcXMLschemaTableValidate1.sql in ScottChangDB of SQL Server 2012 Management Studio (SSMS2012)
-- saved in C:\Documents\XQuery-SQLServer2012
tried to run: 15 April 2015 ??? AM
USE ScottChangDB;
GO
CREATE XML SCHEMA COLLECTION dbo. ComplexTestSchemaCollection_all
AS
N'<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="marvel">
<xsd:complexType>
<xsd:all>
<xsd:element name="avenger_name" />
<xsd:element name="ID" />
</xsd:all>
</xsd:complexType>
</xsd:element>
</xsd:schema>';
GO
DECLARE @x XML (dbo. ComplexTestSchemaCollection_all);
SET @x = N'<?xml version="1.0"?>
<marvel>
<avenger_name>Thor</name>
<ID>4</ID>
</marvel>';
SELECT @x;
GO
DROP XML SCHEMA COLLECTION dbo.ComplexTestSchemaCollection_all;
GO
I feel that drafted sql is very shaky and it needs the SQL Server XML experts to modify to make it work for me. Please kindly help, exam the coding of my shcXMLTableValidate1.sql and modify it to work.
Thanks in advance,
Scott ChangHi Scott,
2) Yes, FOR XML PATH clause converts relational data to XML format with a specific structure for the "marvel" Table. Regarding validate all the avenger_names, please see below
sample.
DECLARE @x XML
SELECT @x=(SELECT ID ,avenger_name FROM marvel FOR XML PATH('Marvel'))
SELECT @x
SELECT
n.value('avenger_name[1]','VARCHAR(99)') avenger_name,
n.value('ID[1]','INT') ID
FROM @x.nodes('//Marvel') Tab(n)
WHERE n.value('ID[1]','INT') = 1 -- specify the ID here
--FOR XML PATH('Marvel') --uncommented this line if you want the result as element type
3)i.check the xml schema content
--find xml schema collection
SELECT ss.name,xsc.name collection_name FROM sys.xml_schema_collections xsc JOIN sys.schemas ss ON xsc.schema_id= ss.schema_id
select * from sys.schemas
--check the schema content,use the name,collection_name from the above query
SELECT xml_schema_namespace(N'name',N'collection_name')
3)ii. View can be viewed as virtual table. Use a view to list the XML schema content.
CREATE VIEW XSDContentView
AS
SELECT ss.name,xsc.name collection_name,cat.content
FROM sys.xml_schema_collections xsc JOIN sys.schemas ss ON xsc.schema_id= ss.schema_id
CROSS APPLY(
SELECT xml_schema_namespace(ss.name,xsc.name) AS content
) AS cat
WHERE xsc.name<>'sys'
GO
SELECT * FROM XSDContentView
By the way, it would be appreciated if you can spread your questions into posts. For any question, feel free to let me know.
Eric Zhang
TechNet Community Support -
XML Signature using an XPath filter
I want to sign an XML document, just based on the content of a particular element in the document. Based on the jwsdp docs it looked pretty simple, but I'm getting strange results. I'll get the same digest value in the SignedInfo for different Xpath filter strings.
Anybody out there have good luck trying to sign XML documents using Xpath filters?
I'm using JDK 1.5.05 and JWSDP 1.6.
Here is my simple XML doc
<?xml version="1.0" encoding="UTF-8"?>
<myns:whole_doc xmlns:myns="http://namespace.myns.com/test"
attr1="attr_one" attr2="attr_two" attr3="attr_three">
<myns:part_one attr="attr_one">
<myns:tag1>this is part_one tag_one</myns:tag1>
<myns:tag2>this is part_one tag_two</myns:tag2>
</myns:part_one>
<myns:part_two attr="attr_two">
<myns:tag1>this is part_two tag_one</myns:tag1>
<myns:tag2>this is part_two tag_two</myns:tag2>
</myns:part_two>
<myns:part_three attr="attr_three">
<myns:tag1>this is part_three tag_one</myns:tag1>
<myns:tag2>this is part_three tag_two</myns:tag2>
</myns:part_three>
</myns:whole_doc>
When I use an XPath filter = "/myns:whole_doc/myns:part_one" I get the same digest as when I use "/myns:whole_doc/myns:part_two", which is the same digest when I don't use XPath filtering. See example output below
<?xml version="1.0" encoding="UTF-8" ?>
- <myns:whole_doc xmlns:myns="http://namespace.myns.com/test" attr1="attr_one" attr2="attr_two" attr3="attr_three">
- <myns:part_one attr="attr_one">
</myns:part_three>
- <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
- <SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments" />
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1" />
- <Reference URI="">
- <Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
- <Transform Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">
<XPath>/myns:whole_doc/myns:part_two</XPath>
</Transform>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>9D5CFDkWd9bHx65txuHOeXWeTns=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>D686H//H5A0zDrlQx8+0fBNpVeJGgWdTXivlI8S/+WqB/E4oBYzeIQ==</SignatureValue>
</Signature>
</myns:whole_doc>It took me all day, but I did find the answer.
When using XPath filters in references, you can't use XPath exactly the way you would use XPath to find nodes in a document. I can't exactly explain why, but it has to do with the fact that the XPath statement is acting as a filter.
Anyway, to just include the part_one element from the following abbreviated XML
<myns:whole_doc> .....
<myns:part_one> ..... </myns:part_one>
<myns:part_two> .... </myns:part_two>
</myns:whole_doc>
the XPath statement should be "ancestor-or-self::myns:part_one"
to make sure that part_one was part of whole_doc you could use something like
(ancestor-or-self::node() = /myns:whole_doc/myns:part_one)
This allows me to sign a document, but still allow portions outside of whole_doc/part_one to change. -
How to generate xml file with multiple nodes using sqlserver as database in SSIS..
Hi ,
I have to generate the xml file using multiple nodes by using ssis and database is sqlserver.
Can some one guide me on to perform this task using script task?
sudhaWhy not use T-SQL for generating XML? You can use FOR XML for that
http://visakhm.blogspot.in/2014/05/t-sql-tips-fun-with-for-xml-path.html
http://visakhm.blogspot.in/2013/12/generating-nested-xml-structures-with.html
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 -
"for XML path " Oracle equivalent of this SQL expression
SELECT TheID,
REPLACE(
RTRIM(
SELECT StudentID + ' '
FROM StudentinSchoolLocation TL
WHERE (LocationID = Results.LocationID)
FOR XML PATH ('')
) AS StudentIDs,
What is the equivalent of 'For XML path' used above
The goal is to get a concatenated list of the group by columns. Like where ever the location is same , get the studentIds and make a comma seperated list of all ids for common location
Works perfectly in SQL.
Thank youHi,
user6287828 wrote:
The goal is to get a concatenated list of the group by columns. Like where ever the location is same , get the studentIds and make a comma seperated list of all ids for common locationThat's called "String Aggregation"
[AskTom.oracle.com|http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2196162600402] shows several different ways to do it.
I recommend the first one, the user-defined function STRAGG, which you can copy from that page.
On Oracle 10 (and up) you may have a similar function, WM_CONCAT (owned by WMSYS), already installed.
WM_CONCAT is not documented, so you may not want to use it in your Production applications.
STRAGG is not so convenient if the order of items in the concatenated string is important.
In that case, use XMLAGG or SYS_CONNECT_BY_PATH, as shown later in the asktom page.
MODEL can also do ordered string aggregation. -
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 -
How to update XML file using XSLT
Hi there,
I have a "small" issue with exporting data to an XML file using XSLT.
A two steps process is needed to import data from a non-hierarchical XML file into ABAP, change the data, and then update the XML file with new values. The problem is not trivial, since the format of the XML file is a complex one: there are many interdependent elements on the same level, pointing to each other by using id and ref attributes. Based on these values the data can be read and written into an internal table. I use XSLT and XPath for that. So the inbound process is done and seems to work correctly. I have to mention that the file contains much more data than I need. I am working only with a small part of it.
Now the changed data must be exported back into the XML file, meaning that the content of certain elements must be updated. How can this be done with XSLT? I can pass only the internal table to the transformation, so how do I access the XML file in order to update it? I have tried to use the <B>xsl:document()</B> function to access the content of the file store locally on my PC, but it fails each time by throwing and URI exception. I have tried the absolute path without any addition and the path with the file:/// addition. Same result. Please advise.
Many thanks,
Ferenc
P.S. Please provide me with links only if they are relevant for this very matter. I will not give points for irrelevant postings...Now the changed data must be exported back into the XML file, meaning that the content of certain elements must be updated. How can this be done with XSLT?
XSLT approach: check these online tutorial
http://www.xml.com/pub/a/2000/08/02/xslt/index.html
http://www.xml.com/pub/a/2000/06/07/transforming/index.html
ABAP approach:
for example you have the xml (original) in a string called say xml_out .
data: l_xml type ref to cl_xml_document ,
node type ref to if_ixml_node .
create object l_xml.
call method l_xml->parse_string
exporting
stream = xml_out.
node = l_xml->find_node(
name = 'IDENTITY'
ROOT = ROOT
l_xml->set_attribute(
name = 'Name'
value = 'Charles'
node = node
(the above example reads the element IDENTITY and sets attribute name/value to the same)
like wise you can add new elements starting from IDENTITY using various methods available in class CL_XML_DOCUMENT
so how do I access the XML file in order to update it?
you have already read this XML into a ABAP variable right?
Sorry couldnt understand your whole process, why do you need to read local XML file?
Raja -
Special character ( , ) in XML Path (' ')
Hi ,
some times my query use the > or < for few records. But XML path is not supporting these values can you please help me with this. Below is the example for what i am working on .
create table #test (id int ,NAME varchar(50),NAME1 varchar(50),NAME2 varchar(50))
insert into #test
values( 1,NULL,'TEST1','TEST1')
,( 2, 'TEST1',NULL,'TEST12')
,( 3,'TEST2','TEST13',NULL)
,( 4,'TEST2 > ', NULL,NULL)
,( 5,NULL,'TEST15',NULL)
,( 6,NULL, NULL, 'TEST6')
,( 7,'TEST8', 'TEST9', 'TEST7')
,( 8,NULL, NULL, NULL)
WITH unpivo AS (
SELECT id, CASE n WHEN 1 THEN NAME
WHEN 2 THEN NAME1
WHEN 3 THEN NAME2
END AS anyname, n
FROM #test
CROSS APPLY (VALUES(1), (2), (3)) AS n(n)
SELECT t.id, CASE WHEN len(u.concat) > 4
THEN substring(u.concat, 1, len(u.concat) -
4)
ELSE ''
END
FROM #test t
CROSS APPLY (SELECT u.anyname + ' AND '
FROM unpivo u
WHERE u.id = t.id
ORDER BY u.n
FOR XML PATH('')) AS u(concat)
where id = 4
DROP TABLE #testNaomi's solution should work well with: FOR
XML PATH(''),
type).value('.','varchar(max)'))
You can concatenate the columns without using XML.
SELECT
Stuff(ISNULL(NAME +' AND ', '')+ISNULL( NAME1 +' AND ', '')+ ISNULL( NAME2+' AND ',''),
len(ISNULL(NAME +' AND ', '')+ISNULL( NAME1 +' AND ', '')+ ISNULL( NAME2+' AND ',''))-3,4,'')
--Or,
Replace(Stuff(ISNULL(NAME +'|', '')+ISNULL( NAME1 +'|', '')+ ISNULL( NAME2+'|',''),
len(ISNULL(NAME +'|', '')+ISNULL( NAME1 +'|', '')+ ISNULL( NAME2+'|','')),1,''), '|',' AND ')
--SQL Server 2012 , 2014
, ISNULL(Replace(Stuff(concat(name+'|', name1+'|',name2+'|' ), Len(concat(name+'|', name1+'|',name2+'|' )),1,''), '|',' AND '),'') from #test -
I would like to parse an xml document using xpath, see:
http://www.onjava.com/pub/a/onjava/2005/01/12/xpath.html
however, in the documentation (in the link above), it states that I need J2SE 5.0.
Currently, I have:
$ java -version
java version "1.5.0_11"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_11-b03)
Java HotSpot(TM) Client VM (build 1.5.0_11-b03, mixed mode, sharing)
Does that mean that I really have to install J2SE 5.0 in order to use J2SE 5.0's XPath support? Does anybody know anything about getting started with XPath, and whether I can just use my existing version of Java? I've never used XPath.
For more documentation, one can view:
http://www.w3.org/TR/xpath20/
Thank you.I have copied the code for the xpath tutorial on
http://www.onjava.com/pub/a/onjava/2005/01/12/xpath.html
exactly as it is on the tutorial, and imported the correct jars (I think).
But still my code is giving lots of errors!
Granted its my first shot but anyway here's the code and the errors...
package test;
import org.jdom.xpath.*;
import java.io.*;
import javax.xml.xpath.*;
public class XPath {
public static void main (String [] args){
XPathFactory factory = XPathFactory.newInstance();
XPath xPath=factory.newXPath();
XPathExpression xPathExpression=xPath.compile("/catalog/journal/article[@date='January-2004']/title");
File xmlDocument = new File("/home/myrmen/workspace/Testing/test/catalog.xml");
//FileInputStream fis = new FileInputStream(xmldocument);
InputSource inputSource = new InputSource(new FileInputStream(xmlDocument));
String title = xPathExpression.evaluate(inputSource);
String publisher = xPath.evaluate("/catalog/journal/@publisher", inputSource);
String expression="/catalog/journal/article";
NodeSet nodes = (NodeSet) xPath.evaluate(expression, inputSource, XPathConstants.NODESET);
NodeList nodeList=(NodeList)nodes;
SAXBuilder saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser");
org.jdom.Document jdomDocument = saxBuilder.build(xmlDocument);
org.jdom.Attribute levelNode = (org.jdom.Attribute)(XPath.selectSingleNode(jdomDocument,"/catalog//journal[@title='JavaTechnology']" + "//article[@date='January-2004']/@level"));
levelNode.setValue("Intermediate");
org.jdom.Element titleNode = (org.jdom.Element) XPath.selectSingleNode( jdomDocument,"/catalog//journal//article[@date='January-2004']/title");
titleNode.setText("Service Oriented Architecture Frameworks");
java.util.List nodeList = XPath.selectNodes(jdomDocument,"/catalog//journal[@title='Java Technology']//article");
Iterator iter=nodeList.iterator();
while(iter.hasNext()) {
org.jdom.Element element = (org.jdom.Element) iter.next();
element.setAttribute("section", "Java Technology");
XPath xpath = XPath.newInstance("/catalog//journal:journal//article/@journal:level");
xpath.addNamespace("journal", "http://www.w3.org/2001/XMLSchema-Instance");
levelNode = (org.jdom.Attribute) xpath.selectSingleNode(jdomDocument);
levelNode.setValue("Advanced");
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Type mismatch: cannot convert from XPath to XPath
The method compile(String) is undefined for the type XPath
InputSource cannot be resolved to a type
InputSource cannot be resolved to a type
NodeSet cannot be resolved to a type
NodeSet cannot be resolved to a type
NodeList cannot be resolved to a type
NodeList cannot be resolved to a type
SAXBuilder cannot be resolved to a type
SAXBuilder cannot be resolved to a type
The method selectSingleNode(Document, String) is undefined for the type XPath
The method selectSingleNode(Document, String) is undefined for the type XPath
Duplicate local variable nodeList
The method selectNodes(Document, String) is undefined for the type XPath
Iterator cannot be resolved to a type
The method newInstance(String) is undefined for the type XPath
The method addNamespace(String, String) is undefined for the type XPath
The method selectSingleNode(Document) is undefined for the type XPath
at test.XPath.main(XPath.java:12)
Maybe you are looking for
-
Whats the Maximum Payload Size XI can handle? We are expecting one of our outbound IDOC to a size of 7.37 MB's and we are not sure Whether XI is capable of handling this size?
-
GNU Screen mouse scrolling shows only empty lines
Hi, I've got a problem with using my mouse wheel to scroll in GNU Screen. This is the content of my .screenrc: defscrollback 10000 hardstatus off termcapinfo xterm* ti@:te@ altscreen on With this settings, It kinda works: I can scroll up, but instead
-
How i can change the bookmarks path onto firefox 36 to the homeuser folder
Hello i have to store only the bookmarks on a homeuser folder and not the hole profile. is there a solution to do that with firefox version 36.0 without addons? I have try with a file and the following text: user_pref("browser.bookmarks.file", "h:\\p
-
Create sets automatically or using a program
Hi, Is there away to automatically create or change sets, transaction code GS01 and GS02, from using a FM or BAPI? I have to create basic sets and single sets. How have you handled this? Is it a manual procedure that one will have to maintain the se
-
Tuxedo XA connect to oracle 10g Failed
env: SUSE 10 entriprise server tuxedo 9.1 no patch oracle 10.2.0 for linux(I dont know 32 or 64 bit) tuxedo\udataobj\RM:Oracle_XA:xaosw:-L${ORACLE_HOME}/lib ${ORACLE_HOME}/precomp/lib/cobsqlintf.o -lclntsh buildtms -o TMS_ORA10g -r Oracle_xa ubb OPEN