how to change xml node value in Jscript?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-25 02:59:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!