问题
I need to change node value with today's date using jscript
XML file
<?xml version="1.0" encoding="ISO-8859-1"?>
<scraping Test>
<General>
<FormatVersion>1</FormatVersion>
<FromDate>2/28/2019 00:00:00</FromDate>
<ToDate>2/28/2019</ToDate>
</General>
</scraping Test>
Jscript (tried using 2 methods)
var dom = new ActiveXObject("Microsoft.XMLDOM");
pathToXML = "Y:\Analysis33.xml" ;
dom.loadxml(pathToXML);
mydate = date();
myVar1 = mydate & " 00:00:00" ;
myVar2 = mydate ;
nNode = xmlDoc.selectsinglenode ("FromDate") ;
nNode.text = myvar1 ;
strResult = xmldoc.save(pathtoxml) ;
I have tried MSXML2.DOM also similar code, but did not work.
var objXML = new ActiveXObject("MSXML2.DOMDocument");
回答1:
Biggest problem is your XML is invalid and unparseable by any recipe of JScript sorcery until you fix it. Get rid of the illegal space in your <scraping Test>
tag. Make it <scrapingTest>
or <root>
.
You also need to select the text()
node in your XPath, then modify the resulting node's .data
property.
Other than that, fix all the cAmElCaSe disagreement in your code and get your date formatting under control. Using this XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<scrapingTest>
<General>
<FormatVersion>1</FormatVersion>
<FromDate>2/28/2019 00:00:00</FromDate>
<ToDate>2/28/2019</ToDate>
</General>
</scrapingTest>
This code works for me to parse and modify it:
var dom = WSH.CreateObject("MSXML2.DOMDocument.6.0"),
pathToXML = WSH.Arguments(0);
dom.load(pathToXML);
var nNode = dom.selectSingleNode("//FromDate/text()"),
today = new Date();
nNode.data = [today.getMonth(), today.getDate(), today.getFullYear()].join('/') + ' 00:00:00';
dom.save(pathToXML);
来源:https://stackoverflow.com/questions/54992570/how-to-change-xml-node-value-in-jscript