如何使用JQuery在xml中获取指定标签的直接子级

时间:2018-10-08 06:00:04

标签: javascript jquery xml children xml-documentation

请检查以下代码。我只需要检查在父标记内定义的子代。

如果该父母中出现任何意外的孩子,我需要将其报告为错误。

这是我的XML文件:

<places>
  <Tirunelveli>XXXX</Tirunelveli>//allowed child of places
  <Tiruchendur></Tiruchendur>//allowed child of places
  <Alwar></Alwar>//allowed child of places
  <sweet></sweet>//not allowed child of places and i have to report this tag as error
</places>

我需要检查<places>父对象是否只有允许的子标记。否则,我需要将其添加为错误。

var rd = new FileReader();
rd.onload = function(e){  
var xmlDoc = $.parseXML(this.result);                   
var $xml = $(xmlDoc);
//check allowed child of front tag
check_allowed_direct_child("places", "Tirunelveli,Tiruchendur,Alwar", "RULE_002", "Fail");                  

//Function to check the x tag have only the alowed child y
function check_allowed_direct_child(x,y,rule,error_type)
{
    var child_array = y.split(',');
    var child_count=child_array.length;
    var ischild=""
    var xmlchild="";
    $xml.children(x).each(function()
    {
        ischild="no";
        xmlchild=this.value;
        for(i=0;i<count;i++)
        {
        if(child_array[i]==xmlchild)
        {
            ischild="yes";
        }
        }
        if(ischild=="no")
        {
            //count the total error and warnings
            check_total_error_warning(error_type);
            $("#validation_report").append('<tr class="err"><td><a href="Asset\Rules\Rule.html\#'+rule+'">'+rule+'</td><td><span class="highlight">&#x0003C;'+xmlchild+'&#x0003E;</span> is not allowed inside the <span class="highlight">&#x0003C;'+x+'&#x0003E;</span> element</td><td class="'+classname+'">'+error_type+'</td></tr>');
            }

            });
            }

};rd.readAsText(this.files[i]);

但是children()代码无法正常工作。我在做什么错了?

2 个答案:

答案 0 :(得分:1)

选择父节点的方式需要更正:使用find进行定位,然后对该结果使用children(不带参数)以获取所有子节点。

如果父节点是XML的根,那么find将找不到它,但是使用addBack,您也可以在匹配项中包含根节点。

我还将使用camelCase作为您的函数名称,并使用jQuery函数构建动态HTML。

这是看起来如何:

var $xml = $("<aa><bb></bb><cc></cc><dd></dd><ee></ee></aa>");
var className = "someClass"
 
//check allowed child of front tag
checkChildAllowed($xml, "aa", ["bb","cc","dd"], "RULE_002", "Fail");                   

//Function to check the x tag have only the allowed child y
function checkChildAllowed($xml, parent, allowedChildren, rule, errorType) {
    // Make sure to first locate the parent correctly:
    var $parent = $xml.find(parent).addBack(parent); 
    // Uppercase tag names as jQuery uses that HTML convention
    allowedChildren = allowedChildren.map(childName => childName.toUpperCase()); 
    $parent.children().each(function () {
        if (allowedChildren.includes(this.nodeName)) return; // tag is OK
        // Include this if that function is defined:
        //check_total_error_warning(error_type); 
        $("#validation_report").append( // Use jQuery functions
            $("<tr>").addClass("err").append(
                $("<td>").append(
                    $("<a>").attr("href", "Asset\Rules\Rule.html\#"+rule).text(rule)
                ),
                $("<td>").append(
                    $("<span>").addClass("highlight")
                               .text("<"+this.nodeName.toLowerCase()+">"),
                    " is not allowed inside the ",
                    $("<span>").addClass("highlight").text("<"+parent+">"),
                    " element"
                ),
                $("<td>").addClass(className).text(errorType)
            )
        );
    });
}
table { border-collapse: collapse }
td { border: 1px solid; padding: 5px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="validation_report"></table>

答案 1 :(得分:0)

您可以做的是,在您选择的父元素中遍历子元素。在这种情况下,您的父元素是“ places”

您可以使用JavaScript函数.tagName来获取子元素的元素类型。然后,您可以围绕该条件构造一个条件,以检查允许/不允许的孩子。

示例:

var rd = new FileReader();
var xmlDoc = $.parseXML(this.result);                   
var $xml = $(xmlDoc);
var classname='errorClass';

function check_allowed_direct_child(x="places",
				    y="Tirunelveli,Tiruchendur,Alwar",
                                    rule="RULE_002",
                                    error_type="Fail") {
    var notAllowedChild='sweet';
    var child_array=y.split(",");
    for(i=0; child_array.length > i; i++) {
        if(child_array[i] != notAllowedChild) {
	    alert(child_array[i]+' is an allowed child');
	}
    }
    $(''+x).children().each(function () {
        var elements=this.tagName.toLowerCase();
	if(elements == notAllowedChild) {
	    alert(elements+' is not an allowed child');
            $("#validation_report").append('<tr class="err"><td><a href="#">'+rule+'</td><td><span class="highlight">&#x0003C;'+elements+'&#x0003E;</span> is not allowed inside the <span class="highlight">&#x0003C;'+x+'&#x0003E;</span> element</td><td class="'+classname+'">'+error_type+'</td></tr>');
	}
    });
}
table, th, td {
   border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<places>
  <Tirunelveli>XXXX</Tirunelveli>
  <Tiruchendur></Tiruchendur>
  <Alwar></Alwar>
  <sweet></sweet>
</places>
<table id="validation_report"></table>
<br />
<button onclick="check_allowed_direct_child();">Test</button>