AutoHotkey Homepage AutoHotkey Community
Let's help each other out
 
 FAQFAQ   SearchSearch   MemberlistMemberlist   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

xpath v3 - read and write XML documents with XPath syntax
Goto page Previous  1, 2, 3 ... 25, 26, 27, 28  Next
 
Post new topic   This topic is locked: you cannot edit posts or make replies.    AutoHotkey Community Forum Index -> Scripts & Functions
View previous topic :: View next topic  
Author Message
aka_bigred



Joined: 22 Jul 2008
Posts: 7

PostPosted: Tue Mar 17, 2009 12:21 am    Post subject: Reply with quote

Thalon - You need to add a new node with the [+1] functionality in your xpath.

Here's my code to add a new question to my XML file and then the answer and points nodes below that. Be sure you create any/all parents before you try creating children of them or it won't work. Below I create the question AND the num nodes in the same statement, but the rest I just have to create & set the siblings to num.
Code:

    ;;If the question exists already, delete it so we can re-save
    if( xpath(theXML, "/root/table[num=" . tableNum . "]/question[num=" . question . "]/count()")  )
    {
        xpath(theXML, "/root/table[num=" . tableNum . "]/question[num=" . question . "]/remove()")
    }

    ;;Save all the properties for the question here
    xpath(theXML, "/root/table[num=" . tableNum . "]/question[+1]/num[+1]/text()", question )
    xpath(theXML, "/root/table[num=" . tableNum . "]/question[num=" . question . "]/answer[+1]/text()", answer )
    xpath(theXML, "/root/table[num=" . tableNum . "]/question[num=" . question . "]/points[+1]/text()", points )


My XML file for reference:
Code:

<root> 
  <table>
    <num>3</num>
    <pad>30</pad>
    <question>
      <num>1</num>
      <answer>1</answer>
      <points>0</points>
    </question>
    <question>
      <num>4</num>
      <answer>1</answer>
      <points>1</points>
    </question>
  </table>
</root>
Back to top
View user's profile Send private message
Thalon



Joined: 12 Jul 2005
Posts: 632

PostPosted: Tue Mar 17, 2009 12:48 am    Post subject: Reply with quote

Ah thank you, that was the missing hint!

Thalon
_________________
AHK-Icon-Changer
AHK-IRC
deutsches Forum
Back to top
View user's profile Send private message
Thalon



Joined: 12 Jul 2005
Posts: 632

PostPosted: Thu Mar 19, 2009 1:27 pm    Post subject: Reply with quote

Hmm.... there is still one problem Sad (at least one I've discovered so far)
I can't add elements to nodes with an attribute containing a slash!?

Here is a little sample-code:
Code:
IfExist, test.txt
  FileDelete, test.txt
IfExist, test2.txt
  FileDelete, test2.txt

XMLDoc =
(
<files>
</files>
)

xpath_load(XMLDoc)
xpath(XMLDoc, "/files/file[+1]/@name/text()", "My Test")
xpath(XMLDoc, "/files/file[@name='My Test']/Sprache[+1]/text()", "Test1")
xpath_save(XMLDoc, "test.txt")
msgbox See test.txt
xpath(XMLDoc, "/files/file[+1]/@name/text()", "My/Test")
xpath(XMLDoc, "/files/file[@name='My/Test']/Sprache[+1]/text()", "Test2")
xpath_save(XMLDoc, "test2.txt")
msgbox See test2.txt


The resulting file test2.txt doesn't please me:
Code:
<?xml version="1.0" encoding="iso-8859-1"?>
<files>
  <file name="My Test">
    <Sprache>Test1</Sprache>
  </file>

  <file name="My/Test" />
</files>
Even if the code is the same except the slash in the attributes value the result is different (no language(Sprache)-node for "My/Test"; Compare green and right node above).
Is there a way to "mask" the slash (and other problematic signs) to get this code working? Or will I have to find a way to workaround this (by replacing the character for example)?

Thx for your help!
Thalon, XML noob Smile
_________________
AHK-Icon-Changer
AHK-IRC
deutsches Forum
Back to top
View user's profile Send private message
Thalon-n-l-i
Guest





PostPosted: Fri Mar 20, 2009 10:38 am    Post subject: Reply with quote

Found the problem so far, it's a bug in xpathv3

Code:
   ; resolve xpath components to: absolute node path, attributes and predicates (if any)
   Loop, Parse, step, /
At this position it splits my text in 2 halfs at the literal slash. Therefore the resulting path is wrong and it doesn't find the right node. Sad

I'm trying to fix it myself, but I've to step into the code...

Thalon
Back to top
Thalon



Joined: 12 Jul 2005
Posts: 632

PostPosted: Fri Mar 20, 2009 11:01 am    Post subject: Reply with quote

I've added a quick-n-dirty fix for the problem:
Code:
  ;Loop added by Thalon to remove a problem with slash in node-values.
   Loop, Parse, step, '
   {
    if ReplaceSlashInNextNode = 1
    {
      StringReplace, NewNodeValue, A_LoopField, /, %scb%, All
      StringReplace, step, step, %A_LoopField%, %NewNodeValue%
    }
    if InStr(A_LoopField, "=")
      ReplaceSlashInNextNode = 1
    else
      ReplaceSlashInNextNode = 0
  }


   ; resolve xpath components to: absolute node path, attributes and predicates (if any)
   Loop, Parse, step, /,
   {
      s = %A_LoopField%

      StringReplace, s, s, %scb%, /, All  ;added by Thalon to remove a problem with slash in node-values.
      If (InStr(s, "*") == 1) ; regex mode for wildcards
      {
         re = 1
         s := "(?:\w+:)?\w+" . SubStr(s, 2)
      }
Search for the red-marked-part in xpath v3 and replace it with the whole snippet. My added code is marked blue.

I've used the end-of-file-character (in variable "scb") to replace the slash, because it isn't an allowed character and shouldn't cause any harm there..
_________________
AHK-Icon-Changer
AHK-IRC
deutsches Forum
Back to top
View user's profile Send private message
greynite



Joined: 17 May 2008
Posts: 32
Location: Dallas, TX

PostPosted: Fri Mar 20, 2009 3:54 pm    Post subject: Reply with quote

Titan wrote:
xpath4 alpha available at http://www.autohotkey.net/~Titan/repos/xpath4.ahk more details later.


Is the code at this link current? And if I'm still having issues, would you suggest I try to tweak version 3, or version 4?

(The fact that I get to even ask such a question is awesome -- thanks Titan!)

Cheers,
Shawn
Back to top
View user's profile Send private message
eulancer



Joined: 23 Mar 2009
Posts: 5

PostPosted: Sun Mar 29, 2009 7:28 am    Post subject: a problem about how to add new node into xml Reply with quote

Firstly,I am not a native English speaker,so there may be some ambiguous expresions.I plan to use xpath.ahk to add new information in to a xml document.
my code is below
Code:

   username=marry
   userage=18
   XMLfile = %A_ScriptDir%\test.xml
   xpath_load(xml, XMLfile)
   xpath(feed, "/UserList/User[+1]/text()",username)
   path(feed, "/NameList/User[".username."]/Userage[+1]/text()", userage)
   path(feed, "/NameList/User[".username."]/AddDate[+1]/text()", A_DD . "/" . A_MM . "/" . A_YYYY)
   xpath_save(feed, XMLfile)

But the it show a error.
the tip is that the follow variable name contains an illegal character:username."]
addiontally,when I am not putting the variable name into this parameter,the xpath.ahk works.But the xml file's is only covered by the new content, not added. how can I add new content in xml file?
please give me a way to solve this problem.thanks for everyone who give a galance on this.


Last edited by eulancer on Sun Mar 29, 2009 11:21 am; edited 1 time in total
Back to top
View user's profile Send private message
DHMH



Joined: 17 Jul 2008
Posts: 194

PostPosted: Sun Mar 29, 2009 10:18 am    Post subject: Reply with quote

Code:
 username:= "marry" ; or username = marry
   userage:=18
   XMLfile = %A_ScriptDir%\test.xml
   xpath_load(xml, XMLfile)
   xpath(feed, "/UserList/User[+1]/text()",username)
   path(feed, "/NameList/User[".[u]username."][/u]/Userage[+1]/text()", userage)
   path(feed, "/NameList/User[".username."]/AddDate[+1]/text()", A_DD . "/" . A_MM . "/" . A_YYYY)
   xpath_save(feed, XMLfile)

Greets,
DHMH Laughing
_________________
Tips & Tricks for Windows XP and Vista... only german! sorry!
German Computerboard
Back to top
View user's profile Send private message Visit poster's website
eulancer



Joined: 23 Mar 2009
Posts: 5

PostPosted: Sun Mar 29, 2009 11:15 am    Post subject: Reply with quote

DHMH,thank you for pointing out my mistake. However, after correctting the code as you said,it still show the the same mistake that I have post before
Back to top
View user's profile Send private message
Tuncay



Joined: 07 Nov 2006
Posts: 893
Location: Berlin, DE

PostPosted: Sun Mar 29, 2009 12:06 pm    Post subject: Reply with quote

Try to make spaces around variable and dot for merging strings in expressions. Here a general example:

Code:
greeting := "Hello "
greeting := greeting . "world. I am from Mars."


instead of greeting."world"
Back to top
View user's profile Send private message
eulancer



Joined: 23 Mar 2009
Posts: 5

PostPosted: Mon Mar 30, 2009 1:19 pm    Post subject: Reply with quote

thank you.my problem has been solved
Code:

StringSplit, TemArray, AddArrayInfo,`n, `r
     xpath_load(pb, "inforamation.xml")
     xpath(pb, "/inforamation/person[+1]/Name[+1]/text()", TemArray1)
     xpath(pb, "/inforamation/person[last()]/Duration[+1]/text()", TemArray2)
     xpath(pb, "/inforamation/person[last()]/Address[+1]/text()", TemArray3)
     ;写入xml文件
     xpath_save(pb, "inforamation.xml")


my code is above
Back to top
View user's profile Send private message
BoBoł
Guest





PostPosted: Mon Mar 30, 2009 3:14 pm    Post subject: Reply with quote

Has anyone already fiddled with [Klipfolio Personal Dashboard (free)] + AutoHotkey ??
I'd be very interested to see how it could be connected smoothly to operational things like process logs (after its conversion with AHK)/web alerts/ebay auctions/<your favourite XML output here>

Feel free to bother me with noobish Beta-testing tasks ShockedSmile

Quote:
1. Super Small
Track news, blogs, weather, email, RSS feeds and with less screen space than a single widget. It uses a lot less RAM than sidebars or widgets too.

2. Really Fast
Fast downloads, fast processing, and a fast display mean no waiting.

3. Always On
Klipfolio Dashboard always shows you the latest information and can alert you to important changes too.

Looking for more horsepower? Check out Klipfolio Dashboard for Business.
Features of Klipfolio Personal Dashboard ...

    Resizable Widgets Any Klip (widget) or part of the Klipfolio Dashboard interface can be resized to what works for you.
    Monitor Anything If your Web browser can access it, Klipfolio Dashboard can monitor it. There are over 4000 Klips at Klipfolio.com to get you started.
    RSS Support Monitor, filter and set alerts for your favorite RSS feeds, right on your desktop.
    Sidebars Place your dashboard along any screen edge, so you can always see it while working on other things.
    Skinnable Download skins for your dashboard, change its colours and adjust its fonts.
    Multi-Language Full unicode support (over 24 languages) in Klipfolio Dashboard's interface and in any Klips.
    Desktop Alerts Set desktop alerts for keywords and new articles in any Klip so you are notified as soon as changes occur.
    Developer-Friendly Klips are smart, easy to build, and fully scriptable. You can write a Klip in as little as 7 lines of XML.
Back to top
Tuncay



Joined: 07 Nov 2006
Posts: 893
Location: Berlin, DE

PostPosted: Mon Apr 13, 2009 9:04 pm    Post subject: Reply with quote

Tuncay wrote:
I am trieng to upgrade from version 1 of xpath to version 3 and have massive problems. I try to update all old xpath occurrence with new calls.

In old days with xpath 1, I did often this:
Code:
ConfigDoc := XmlDoc(ConfigFile)
NodeCommands := XPath(ConfigDoc, "/hiscoreRecConfig/commands")
MsgBox % XPath(NodeCommands, "/hiscoreRecConfig/commands/command[@name=mame]/command/text()")


to enable faster calls, because in this case xpath() does not need to search full document, just the little section which is needed. (this works.)

If I now try this with xpath 3, ill get empty string:
Code:
xpath_load(ConfigDoc, ConfigFile)
NodeCommands := XPath(ConfigDoc, "/hiscoreRecConfig/commands")
MsgBox % XPath(NodeCommands , "/hiscoreRecConfig/commands/command[@name=mame]/command/text()")
(changed a copy paste error)

it does not work anymore. I want use subsets / parts of a xml file. Why does it not work? On bigger xml files, could this not be a speed up at Loops with high frequently calls of same subset?

Here is the configuration file:
Code:
<?xml version="1.0" encoding="iso-8859-1"?>

<hiscoreRecConfig>
    <options>
        <option name="autoSave">0</option>
        <option name="exportAutoRun">1</option>
        <option name="scoreDelimChar">,</option>
        <option name="searchMatchType">InStr</option>
        <option name="speedCompareThreshold">5</option>   
        <option name="listTitleCount">12</option> 
        <option name="defaultLabelName1">stage</option>
        <option name="defaultLabelName2">vehicle</option>
        <option name="defaultLabelName3">character</option>
    </options>
    <users>
        <user name="player">Tuncay</user>
        <user name="rival">Akira</user>
    </users>
    <path>
        <file name="var">var.ini</file>
        <file name="highscores">hiscore.xml</file>
        <folder name="backup">backup</folder>
        <folder name="programs">bin</folder>
        <folder name="cache">cache</folder>
        <folder name="export">export</folder>
        <folder name="highscores">inp</folder>
        <folder name="snap">snap</folder>
        <folder name="ico">icons</folder>
    </path>
    <commands>
        <command name="mame">E:\Tuncay\Emulatoren\Mame\Mamepp.exe</command>
        <command name="compress">bin\7z.exe a -t7z -mx1</command>
        <command name="uncompress">bin\7z.exe e</command>
        <command name="scripteditor">C:\Programme\Vim\vim72\gvim.exe</command>
        <command name="editor">C:\Programme\Vim\vim72\gvim.exe</command>
    </commands>
</hiscoreRecConfig>


Now I got it to work. There was not any problem with that. After
Code:
NodeCommands := xpath(ConfigDoc, "/hiscoreRecConfig/commands")

the variable
Code:
NodeCommands

contains the right node. But MsgBox is not able to show the content from that variable. The variable must be reformatted with
Code:
xpath_load(NodeCommands)

and then accessing in following way
Code:
MsgBox % XPath(NodeCommands , "/commands/command[@name=mame]/text()")

should show
Quote:
E:\Tuncay\Emulatoren\Mame\Mamepp.exe


note: xpath v3 is twice slower than xpath v1 but less buggy and works great.
Back to top
View user's profile Send private message
gregster



Joined: 19 Mar 2009
Posts: 9

PostPosted: Thu Apr 16, 2009 9:15 pm    Post subject: Reply with quote

Hi there,

hopefully you can help me. I have a problem with hyphens ("-") in node-names, like for example <sur-name>. Nothing is returned in these cases when I try to fetch the text.

I use this script for testing:
Code:

xml := xpath_load(xmlvar, "test2.xml")

name := xpath(xmlvar, "/addressBook/address[2]/firstName/text()")
   msgbox %name%
name := xpath(xmlvar, "/addressBook/address[2]/sur-name/text()")
   msgbox %name%


This is the test2.xml file that I use (it is not the actual xml file that I download from the internet), but anyway it should work the same way:
Code:

<addressBook>
     <address>
          <firstName>John</firstName>
          <sur-name>Smith</sur-name>
          <email>smithj@world.org</email>
          <tel type = "work">234-123-222</tel>
     </address>
     <address>
          <firstName>Alice</firstName>
          <sur-name>Brown</sur-name>
          <email>Alice.Brown@europe.com</email>
          <tel type = "home">22-33-444</tel>
          <tel type = "work">11-43-222</tel>
     </address>
     <address>
          <firstName>George</firstName>
          <sur-name>White</sur-name>
          <email>gw@rock.com</email>
     </address>
</addressBook>



There is probably some parsing problem with the hyphen. A work-around would probably be to replace the hyphens beforehand, but may be there is a easier way...

Thank you in advance for your help.
Back to top
View user's profile Send private message
pkutter



Joined: 18 Mar 2009
Posts: 11
Location: Minnesota, USA

PostPosted: Thu Apr 23, 2009 6:00 pm    Post subject: Trying to write a script that will modify all xml files Reply with quote

I'm trying to write a script to recursively modify all XML files in a user profile folder. I'm not sure if this is a problem with my syntax in AHK or xpath. I suspect that it's either that it doesn't like the space or the @ in the path. My script and error message are below. The MsgBox is only for my debugging purposes and will be removed when it's done. Any assistance would be greatly appreciated.


AHK Script

Code:

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.
#include xpath.ahk





Loop, %A_AppData%\Pandion\Profiles\settings.xml, , 1  ; Recurse into subfolders.

{
    xpath_load(%A_LoopFileFullPath%) ; load an XML document
    xpath(xmlfile, "settings/history_store() ", "true")
   
   
   
    MsgBox, 4, , Filename = %A_LoopFileFullPath%`n`nContinue?
    IfMsgBox, No
        break

   
    xpath_save(%A_LoopFileFullPath%, feed) ; write XML
   
}





And here's the error

---------------------------
updatepandionlogging.ahk
---------------------------
Error: The following variable name contains an illegal character:
"\\server\RedirectedFolders\usernameremoved\Application Data\Pandion\Profiles\admin@chat.domain.local\settings.xml"

The current thread will exit.

Line#
448: }
449: StringReplace,doc,xml,,,,,All
450: NumPut(0, doc := " " . doc, 0, "UChar")
451: Return,true
452: }
020: Loop,%A_AppData%\Pandion\Profiles\settings.xml,,1
022: {
---> 023: xpath_load(%A_LoopFileFullPath%)
024: xpath(xmlfile, "settings/history_store() ", "true")
028: MsgBox,4,,Filename = %A_LoopFileFullPath%

Continue?
029: IfMsgBox,No
030: Break
033: xpath_save(%A_LoopFileFullPath%, feed)
035: }
035: Exit

---------------------------
OK
---------------------------
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   This topic is locked: you cannot edit posts or make replies.    AutoHotkey Community Forum Index -> Scripts & Functions All times are GMT
Goto page Previous  1, 2, 3 ... 25, 26, 27, 28  Next
Page 26 of 28

 
Jump to:  
You can post new topics in this forum
You can reply to topics in this forum


Powered by phpBB © 2001, 2005 phpBB Group