How do I reach the second child node of an element XML in vbscript? - vbscript

After spending many hours on the internet I was not able to get this to work and need some help.
XML:
xml snippet highlighting NoteSynopsis
CODE:
set xmlDoc = SERVER.CREATEOBJECT("MSXML2.DomDocument.6.0")
xmlDoc.async = False xmlDoc.Load("D:\GVPApplications\TechSupportCreateIncident\CreateIncidentRequest.xml")
xmlDoc.setProperty "NewParser","true"
set Root = xmlDoc.documentElement
set NodeList1 = Root.getElementsByTagName("IncidentNote")
For Each Elem in NodeList1
if Elem.firstChild.nodename = "Note" then
Elem.firstChild.text = Notes
end if
Next
ISSUE:
As highlighted in the image XML , I need to be able to read "NoteSynopsis" element and its value. As simple as this seems I have not been able to find a solution to this. If this was the last child no issue, I would do a Elem.LastChild.nodename, but this isn't!

You could use the selectSingleNode(...) method and use XPath
set xmlDoc = SERVER.CREATEOBJECT("MSXML2.DomDocument.6.0")
xmlDoc.async = False xmlDoc.Load("D:\GVPApplications\TechSupportCreateIncident\CreateIncidentRequest.xml")
xmlDoc.setProperty "NewParser","true"
xmlDocument.setProperty "SelectionLanguage", "XPath"
Dim firstIncidentNote
set firstIncidentNote = xmlDoc.SelectSingleNode("//IncidentNote")
Dim note
Dim noteSynopsis
set note = firstIncidentNote.GetAttribute("Note")
set note = firstIncidentNote.GetAttribute("NoteSynopsis")
https://msdn.microsoft.com/en-us/library/ms757846(v=vs.85).aspx

Related

Access 2010 - Run-time error 3022

I'm trying to add records to an exisiting table called "Topics" (section as of "For Each SelectedTopic In SelectedTopicsCtl.ItemsSelected" in the code below).
When executing the code i always get "Run-time error '3022': The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. So it goes wrong at the creation of the Autonumber in the field "ID" (= the only field that is indexed - no duplicates).
When debugging, line "TopicRecord.Update" in the code below is highlighted.
I have read several posts on this topic on this forum and on other forums but still cannot get this to work - i must be overlooking something....
Private Sub Copy_Click()
Dim JournalEntrySourceRecord, JournalEntryDestinationRecord, TopicRecord As Recordset
Dim JournalEntryToCopyFromCtl, JournalEntryToCopyToCtl, JournalEntryDateCreatedCtl, SelectedTopicsCtl As Control
Dim Counter, intI As Integer
Dim SelectedTopic, varItm As Variant
Set JournalEntryToCopyFromCtl = Forms![Copy Journal Entry]!JournalEntryToCopyFrom
Set JournalEntryToCopyToCtl = Forms![Copy Journal Entry]!JournalEntryToCopyTo
Set JournalEntryDateCreatedCtl = Forms![Copy Journal Entry]!JournalEntryDateCreated
Set JournalEntrySourceRecord = CurrentDb.OpenRecordset("Select * from JournalEntries where ID=" & JournalEntryToCopyFromCtl.Value)
Set JournalEntryDestinationRecord = CurrentDb.OpenRecordset("Select * from JournalEntries where ID=" & JournalEntryToCopyToCtl.Value)
Set SelectedTopicsCtl = Forms![Copy Journal Entry]!TopicsToCopy
Set TopicRecord = CurrentDb.OpenRecordset("Topics", dbOpenDynaset, dbSeeChanges)
With JournalEntryDestinationRecord
.Edit
.Fields("InitiativeID") = JournalEntrySourceRecord.Fields("InitiativeID")
.Fields("DateCreated") = JournalEntryDateCreatedCtl.Value
.Fields("Comment") = JournalEntrySourceRecord.Fields("Comment")
.Fields("Active") = "True"
.Fields("InternalOnly") = JournalEntrySourceRecord.Fields("InternalOnly")
.Fields("Confidential") = JournalEntrySourceRecord.Fields("Confidential")
.Update
.Close
End With
JournalEntrySourceRecord.Close
Set JournalEntrySourceRecord = Nothing
Set JournalEntryDestinationRecord = Nothing
For Each SelectedTopic In SelectedTopicsCtl.ItemsSelected
TopicRecord.AddNew
For Counter = 3 To SelectedTopicsCtl.ColumnCount - 1
TopicRecord.Fields(Counter) = SelectedTopicsCtl.Column(Counter, SelectedTopic)
Next Counter
TopicRecord.Fields("JournalEntryID") = JournalEntryToCopyToCtl.Value
TopicRecord.Fields("DateCreated") = JournalEntryDateCreatedCtl.Value
TopicRecord.Update
Next SelectedTopic
TopicRecord.Close
Set TopicRecord = Nothing
End Sub
First, your Dims won't work as you expect. Use:
Dim JournalEntrySourceRecord As Recordset
Dim JournalEntryDestinationRecord As Recordset
Dim TopicRecord As Recordset
Second, it looks like you get your ID included here:
TopicRecord.Fields(Counter)
or Topic is a query that includes it somehow. Try to specify the fields specifically and/or debug like this:
For Counter = 3 To SelectedTopicsCtl.ColumnCount - 1
TopicRecord.Fields(Counter).Value = SelectedTopicsCtl.Column(Counter, SelectedTopic)
Debug.Print Counter, TopicRecord.Fields(Counter).Name
Next Counter

Object doesn't support this property or method: 'xmldoc2.importNode'

I am trying to copy nodes from one XML document into another.
Project is a root element inboth documents and I want to select all ItemGroup elements from first document and insert them before Import element in the second document. Unfortunately, I get
Object doesn't support this property or method: 'xmldoc2.importNode'
Here is the code I am using:
Set xmldoc1 = CreateObject("Microsoft.XMLDOM")
xmldoc1.async = false
xmldoc1.load WScript.Arguments(0)
Set xmldoc2 = CreateObject("Microsoft.XMLDOM")
xmldoc2.async = false
xmldoc2.load WScript.Arguments(1)
Set importNode = xmldoc2.selectSingleNode("//Project/Import")
Set nodes = xmldoc1.selectNodes("//Project/ItemGroup")
For Each node In nodes
Set newNode = xmldoc2.importNode(node, True)
xmldoc2.insertBefore newNode, importNode
Next
How should I fix the code?
EDIT:
Thanks to #Ekkehard.Horner, I solved the issue. Here is the updated code
Set xmldoc1 = CreateObject("Microsoft.XMLDOM")
xmldoc1.async = false
xmldoc1.load WScript.Arguments(0)
Set xmldoc2 = CreateObject("Microsoft.XMLDOM")
xmldoc2.async = false
xmldoc2.load WScript.Arguments(1)
Set importNode = xmldoc2.selectSingleNode("//Project/Import")
Set nodes = xmldoc1.selectNodes("//Project/ItemGroup")
For Each node In nodes
Set newNode = node.cloneNode(true)
xmldoc2.documentElement.insertBefore newNode, importNode
Next
The docs for importNode state:
[This sample code uses features that were first implemented in MSXML
5.0 for Microsoft Office Applications.]
I'd try to use
"Msxml2.DOMDocument" or "Msxml2.DOMDocument.6.0" instead of "Microsoft.XMLDOM"
.cloneNode instead of .importNode

How can I strip the element using vbscript and display in message box?

I would like to find the price with 2 year contract and display it in a message box. Sofar I have:
Dim MyPage
Dim Price
Set MyPage=CreateObject("Microsoft.XMLDOM")
MyPage.load("http://www.verizonwireless.com/b2c/store/controller?item=phoneFirst&action=viewPhoneDetail&selectedPhoneId=5723")
Wscript.Sleep 2000
Set Price = MyPage.getElementsByTagName("span")
For Each Elem In Price
MsgBox(Elem.firstChild.nodeValue)
Next
I understand that I am completely wrong, but I don't even know where to start. I love writing simple programs like this, but I just need help getting started. Any ideas will help!
Here a better version, uses the HTMLFile object
Dim HTMLDoc, XML, URL, table
Set HTMLDoc = CreateObject("HTMLFile")
Set XML = CreateObject("MSXML2.XMLHTTP")
URL = "http://www.verizonwireless.com/b2c/store/controller?item=phoneFirst&action=viewPhoneDetail&selectedPhoneId=5723"
With XML
.Open "GET", URL, False
.Send
HTMLDoc.Write .responseText
End With
Set spans = HTMLDoc.getElementsByTagName("span")
for each span in spans
WScript.Echo span.innerHTML
next
'=><SPAN>Set Location</SPAN>
'=>Set Location
'=><SPAN>Submit</SPAN>
'=>Submit
'=>Connect with us
the control you use is for reading XML documents, you need something like this
'Create an xmlhttp object, the string depends on the version that is installed
'on your pc could eg also be "Msxml2.ServerXMLHTTP.5.0"
Set xmlhttp = CreateObject("Microsoft.XMLHTTP")
xmlhttp.Open "GET", "http://admin:pasword#10.0.0.2/doc/ppp.htm", False
xmlhttp.Send
text=xmlhttp.responseText
wscript.echo text
Set xmlhttp = Nothing
Run a search in your registry for XMLHTTP to get the right string/version for the identifier.
To get the tag from the html you can use the following
text = "blabla <span>this is what i need</span> bla bla<span>second item</span> end"
function getElementsByTagName(sTextToSeachIn, tag)
answer = ""
separator = ""
set oRegExpre = new RegExp
with oRegExpre
.IgnoreCase = true
.Global = true
.MultiLine = True
.Pattern = "<" & tag & ">(.*?)</" & tag & ">"
end with
set oColMatches = oRegExpre.Execute(sTextToSeachIn)
for each match in oColMatches
answer = answer & separator & match.subMatches(0)
separator = "|" 'use something that's not in the spancontents
next
if separator <> "" then
getElementsByTagName = split(answer, separator)
else
getElementsByTagName = array()
end if
end function
for each tag in getElementsByTagName(text, "span")
wscript.echo tag
next
'=>this is what i need
'=>second item
There are better techniques and certainly better languages than vbscript to do this, i suggest to take a look at Ruby which exels in such things.
Alex, in response to your comment about getting a cookie and running a javascript in HTMLFile, here a ruby script i found, hopes it helps you at some point, it reads in a page, passes it to the HTLMFile object and in that DOM executes a remote javascript file. It also gives you an idea of the combined power of activeX and Ruby.
require "win32ole"
$jsxpath_uri = "http://svn.coderepos.org/share/lang/javascript/javascript-xpath/trunk/release/javascript-xpath-latest-cmp.js"
uri, xpath = "http://gist.github.com/gists", "//div[#class='info']/span/a"
http = WIN32OLE.new('MSXML2.XMLHTTP')
http.Open "GET", uri, false
http.Send
text = http.responseText
dom = WIN32OLE.new("htmlfile")
dom.Write(text)
dom.parentWindow.eval(open($jsxpath_uri){|f| f.read })
items = dom.evaluate(xpath, dom, nil, 7, nil)
len = items.snapshotLength
(0...len).each do |i|
item = items.snapshotItem(i)
puts item.innerHTML
end

How to save the active "Word" document in VBScript?

Here I have a small VBS script that helps me append a new line to a table in MS "Word" 2003:
Set wd = CreateObject("Word.Application")
wd.Visible = True
Set doc = wd.Documents.Open ("c:\addtotable.doc")
Set r = doc.Tables(1).Rows.Add
aa = Split("turtle,dog,rooster,maple", ",")
For i = 0 To r.Cells.Count - 1
r.Cells(i + 1).Range.Text = aa(i)
Next
It works fine, but it doesn't save anything. I want it to save the performed changes.
By the method of macro-recording in the "Word" I got this macro command that saves active "Word" document:
ActiveDocument.Save
So, I decided to append this macro to the VBS script above:
Set wd = CreateObject("Word.Application")
wd.Visible = True
Set doc = wd.Documents.Open ("c:\addtotable.doc")
Set r = doc.Tables(1).Rows.Add
aa = Split("turtle,dog,rooster,maple", ",")
For i = 0 To r.Cells.Count - 1
r.Cells(i + 1).Range.Text = aa(i)
Next
ActiveDocument.Save
But it doesn't save anything. What am I doing wrong here?
Have you already tried calling doc.Save after making those changes? If that doesn't work:
The issue is that ActiveDocument doesn't automatically reference what you think it does in VBScript the way it does in Word's VBA.
Try setting a new variable to the active document, like so:
Dim activeDoc
Set activeDoc = wd.ActiveDocument
activeDoc.Save
I think you have to use ActiveDocument.SaveAs("C:\addtotable.doc"); because I can't find any documentation for .Save. SaveAs accepts a second parameter which specifies what format to save it in. Pastebin of the parameters here.

Call out to script to stop with attribute in wWWHomePage

I'm gettinga n error message in line 8 when I try to call out the script to stop when it finds teh attribute in the Web page: field in AD.
Set objSysInfo = CreateObject("ADSystemInfo")
strUserDN = objSysInfo.UserName
Set objUser = GetObject("LDAP://" & strUserDN)
strwWWHomePage = objItem.Get("wWWHomePage")
If wWWHomePage 6 Then
wscript.quit
Else
Set ppt = CreateObject("PowerPoint.Application")
ppt.Visible = True
ppt.Presentations.Open "\\abngan01\tracking\ppt.pptx"
End If
You have:
If wWWHomePage 6 Then
I'm assuming you want it to say:
If wWWHomePage = 6 Then
Since the missing "=" will cause an error, but since that code really doesn't do anything anyway, other than just abort the script, you could simplify your code by only taking action if that value is not set, for example:
If objItem.Get("wWWHomePage") <> 6 Then
Set ppt = CreateObject("PowerPoint.Application")
ppt.Visible = True
ppt.Presentations.Open "\\abngan01\tracking\ppt.pptx"
End If
I'm also assuming "6" is some sort of flag you've set yourself, you might want to use something a little more descriptive like "PPTSTATUS006", or something along those lines.

Resources