一道javascript面试题

It'll be a jscript function to transform a given format of XML input to another XML format.

The input would be like:


<?xml version="1.0"?>
<menu xmlns="">
    <menuitem>
        <node>0</node>
        <parent>1</parent>
        <name>parent</name>
    </menuitem>
    <menuitem>
        <node>2</node>
        <parent>1</parent>
        <name>1st child</name>
    </menuitem>
    <menuitem>
        <node>3</node>
        <parent>1</parent>
        <name>2nd child</name>
    </menuitem>
    <menuitem>
        <node>4</node>
        <parent>2</parent>
        <name>grantchild</name>
   <attr1>hello</attr1>
   <attr2>World</attr2>
    </menuitem>
</menu>

 

The output would be like:

<?xml version="1.0"?>
<menu xmlns="">
    <menuitem>
        <name>parent</name>
        <menuitem>
            <name>1st child</name>
    <attr1>hello</attr1>
    <attr2>World</attr2>
            <menuitem>
                <name>grand child</name>
            </menuitem>
        </menuitem>
        <menuitem>
            <name>2nd child</name>
        </menuitem>
    </menuitem>
</menu>

In the input format, tag "node" and "parent" specifies the structure of the tree, while "name" and others tags should be copied to the output format.  Therefore, the code should be able to handle the following fragment of XML:

<menuitem>
        <node>2</node>
        <parent>1</parent>
        <name>1st child</name>
        <lastName>Xia</lastName>
        <firstName>Hao</firstName>
</menuitem> 

 

 

两种方式解答:

1.  利用xslt, 文件名 format.xsl

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method = "xml"  omit-xml-declaration = "yes" indent = "yes"/>
<xsl:key name="parentID" match="menuitem" use="parent"/> 
<!--key that can be used in the style sheet with the key() function -->

<xsl:template match="/">
 <xsl:element name="menu" >    <!-- create an element node in the output document. --> 
  <xsl:copy>  
   <xsl:call-template name="formatXml">  
    <xsl:with-param name="root" select="menu"/>  
    <xsl:with-param name="parentID">0</xsl:with-param>  
   </xsl:call-template>  
  </xsl:copy>
 </xsl:element>  
</xsl:template>

<xsl:template name="formatXml">  
   <xsl:param name="parentID">0</xsl:param>  
   <xsl:variable name="nodeList" select="key('parentID',$parentID)"/>  
  <xsl:if test="count($nodeList) &gt; 0">  
     <xsl:for-each select="$nodeList">
 
    <xsl:element name="{name(.)}">  
       <xsl:copy-of select="name"/> 
       <xsl:if test="node = 2">
 
      <xsl:copy-of select="//attr1"/>  
        <xsl:copy-of select="//attr2"/>
       </xsl:if>

       <xsl:call-template name="formatXml">  
        <xsl:with-param name="parentID" select="node"></xsl:with-param>  
       </xsl:call-template>
     </xsl:element>  

     </xsl:for-each>  
    </xsl:if>
</xsl:template>
</xsl:stylesheet>

2. javascript脚本, 文件名Format.js

<!--
//create DOM object
function createDOMObject()
{
 var xmlDoc;
 if (window.ActiveXObject)
 {
  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  }
 else
 {
  alert('Your browser can/'t handle this script');
 }
  return xmlDoc;
}

//Create the error information
function showError(objDocument) {
  var strError = new String;
  strError = 'Invalid XML file !<BR />'
           + 'File URL: ' + objDocument.parseError.url + '<BR />'
           + 'Line No.: ' + objDocument.parseError.line + '<BR />'
           + 'Character: ' + objDocument.parseError.linepos + '<BR />'
           + 'File Position: ' + objDocument.parseError.filepos + '<BR />'
           + 'Source Text: ' + objDocument.parseError.srcText + '<BR />'
           + 'Error Code: ' + objDocument.parseError.errorCode + '<BR />'
           + 'Description: ' + objDocument.parseError.reason
  return strError;
}


function loadXML(xmlDoc, xmlFile)
{
 xmlDoc.async="false";
 xmlDoc.load(xmlFile);
}

//convert the xml to another format xml file
function transformFiles(xmlDoc, xmlXSL, objResults)
{
 //set the property
 xmlDoc.validateOnParse = true;
 xmlXSL.validateOnParse = true;

 //check xml content 
 if (xmlDoc.parseError.errorCode != 0) {
  objResults.innerHTML = showError(xmlDoc)
  return false;
 }

 //check the xslt content
 if (xmlXSL.parseError.errorCode != 0) {
  objResults.innerHTML = showError(xmlXSL)
  return false;
 }

 //convert the xml by xslt
 strResult = xmlDoc.transformNode(xmlXSL);

 //show the content
 objResults.innerHTML = "<xmp>" + strResult + "</xmp>";
 return true;
}

//-->

3. input文件, 文件名input.xml

<?xml version="1.0"?>
<!-- ?xml-stylesheet type="text/xsl" href="convert.xsl"? -->
<menu xmlns="">
    <menuitem>
        <node>1</node>
        <parent>0</parent>
        <name>parent</name>
    </menuitem>
    <menuitem>
        <node>2</node>
        <parent>1</parent>
        <name>1st child</name>
    </menuitem>
    <menuitem>
        <node>3</node>
        <parent>1</parent>
        <name>2nd child</name>
    </menuitem>
    <menuitem>
        <node>4</node>
        <parent>2</parent>
        <name>grantchild</name>
    <attr1>hello</attr1>
    <attr2>World</attr2>
    </menuitem>
</menu>

4.  用xslt转换的html文件

<html>
 <head>
  <style type="text/css">
   body {font-family:Tahoma,Verdana,Arial,sans-serif; font-size:14px}
   .head {font-family:Tahoma,Verdana,Arial,sans-serif; font-size:18px; font-weight:bold}
  </style>
  <script language="javascript" src="Format.js"></script>
  <script language="JScript">
  <!--  
  function formatXmlFile(xmlFile, xslFile)
  {
   var xmlDoc = createDOMObject();
   var xmlXSL = createDOMObject();
   
   loadXML(xmlDoc, xmlFile);
   loadXML(xmlXSL, xslFile);
   
   var objResults = document.getElementById('divResults');
   transformFiles(xmlDoc, xmlXSL, objResults);
  }  
  //-->
  </script>

 </head>
 <body οnlοad="formatXmlFile('input.xml', 'format.xsl')">
  <p><span class="head">Convert the xml to another format xml by XSLT</span></p>
  <h4>output:</h4>
  <hr>
  
  <!-- display the result of converting -->
  <div id="divResults"></div> 
 </body>
</html>

5 用javascript转换的html文件ConvertXMLByJS.html

<html>
 <head>
  <style type="text/css">
   body {font-family:Tahoma,Verdana,Arial,sans-serif; font-size:14px}
   .head {font-family:Tahoma,Verdana,Arial,sans-serif; font-size:18px; font-weight:bold}
  </style>
  <script language="javascript" src="Format.js"></script>
  <script language="JScript">
  <!--  
  var xmlDoc;
  var newXML;
  function formatXmlFile(xmlFile)
  {
   xmlDoc = createDOMObject();   
   loadXML(xmlDoc, xmlFile);
   
   var objResults = document.getElementById('divResults');
 
   newXML = createDOMObject(); 
   newXML.loadXML("<menu xmlns=''> </menu>");
   GetNodeByParentID(); 
  } 
  
  function GetNodeByParentID() 
  {
   var i=1;
   for (i=1;i<=4;i++)
   {
    var currentOldXmlNode = xmlDoc.selectSingleNode("//menuitem[node="+i+"]"); 
    var parentID = currentOldXmlNode.selectSingleNode("parent").text;
    var nodeName  = currentOldXmlNode.selectSingleNode("name").text;

    var parentNode = xmlDoc.selectSingleNode("//menuitem[node='"+parentID+"']");
   
    var currentNewXmlNode;
    if (!parentNode)
    {
     currentNewXmlNode = newXML.documentElement;;
    }
    else
    {
     var parentName = parentNode.selectSingleNode("name").text;
     var currentNewXmlNode = newXML.selectSingleNode("//menuitem[name='"+parentName+"']");  
    }
    var menuitemNode = newXML.createElement("menuitem");
    var newNode = newXML.createElement("name");  
    newNode.text = nodeName; 
    menuitemNode.appendChild(newNode); 
    if ( i == 2) 
    {
     var attr1Node = newXML.createElement("attr1");
     attr1Node.text = xmlDoc.selectSingleNode("//menuitem/attr1").text;
     var attr2Node = newXML.createElement("attr2");
     attr2Node.text =  xmlDoc.selectSingleNode("//menuitem/attr2").text;
     menuitemNode.appendChild(attr1Node);
     menuitemNode.appendChild(attr2Node); 
    }   
    
    currentNewXmlNode.appendChild(menuitemNode); 
   }
   var objResults = document.getElementById('divResults');
   objResults.innerHTML = "<xmp>" + newXML.xml + "</xmp>";
  }
  //-->
  </script>

 </head>
 <body οnlοad="formatXmlFile('input.xml')">
  <form width = '800px'>
   <p><span class="head">Convert the xml to another format xml by JavaScript</span></p>
   <h4>output:</h4>
   <hr>
   
   <!-- display the result of converting -->   
   <div id="divResults" style="width:100px;word-break:break-all;"></div>
  </form> 
 </body>
</html>

 

将上述5个文件放入一个文件夹, 运行,可见运行结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值