将xml属性从文件读入js文件

时间:2018-08-27 18:55:09

标签: javascript jquery html

我正在尝试从XML文档制作一个简单的数据列表。我用几种不同的方法来工作,但是他们不断更改我的XML文档。另请注意,此功能必须在IE,Chrome和Firefox上有效。另请注意,它将在称为Net Forum的CMS中使用。因此,我试图使代码保持真实基础,并避免使用第三方库/插件。我正在尝试使用Jquery,并且可以使用它,但是正如我在更改XML之前所说的那样,现在它需要按属性值而不是Node来读取:

XML代码段:

<PRODUCTS>
  <PRODUCT Category="Leadership and Governance">
    <Product>
      <prd_name>Governance in High Performing Organizations: A Comparative Study of Governing Boards In Not-For-Profit Hospitals</prd_name>
    </Product>
  </PRODUCT>
  <PRODUCT Category="Planning and Strategy">
    <Product>
      <prd_name>Results-Oriented Strategic Planning</prd_name>
    </Product>
  </PRODUCT>
</PRODUCTS>

HTML代码段:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="content/jquery-ui-1.12.1/jquery-ui.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="Scripts/jquery-ui-1.12.1.js"></script>
    <script src="js-auto-complete-3.js"></script>
</head>
<body>
    <div align="center" id="container">
        <font color=#04418e size="6">eWeb Products</font><br><br>
        <div id="search">
            <datalist id="dl_search" style="overflow-y: auto!important"></datalist>
            <select name="filter" id="filter">
                <option value="All" selected="selected">All</option>

                <option value="Coding and Billing">Coding and Billing</option>
                <option value="Data Products">Data Products</option>
                <option value="Design and Construction">Design and Construction</option>
                <option value="Environmental Services">Environmental Services</option>
                <option value="Facilities Management">Facilities Management</option>
                <option value="Health Information Technology">Health Information Technology</option>
                <option value="Human Resources">Human Resources</option>
                <option value="Leadership and Governance">Leadership and Governance</option>
                <option value="Learning Product">Learning Product</option>
                <option value="Marketing and Communications">Marketing and Communications</option>
                <option value="Materials Management">Materials Management</option>
                <option value="Membership">Membership</option>
                <option value="Nursing Leadership">Nursing Leadership</option>
                <option value="Patient Safety Quality and Advocacy">Patient Safety Quality and Advocacy</option>
                <option value="Planning and Strategy">Planning and Strategy</option>
                <option value="Risk Management">Risk Management</option>
                <option value="Social Work">Social Work</option>
                <option value="Volunteers and Auxilians">Volunteers and Auxilians</option>
                <option value="Workforce">Workforce</option>
            </select>
            <input id="txt_search" size="100" />
        </div>
        <br> <br>
    </div>
</body>
</html>

JavaScript代码段:

$(document).ready(function() 
        {
            var DataList = [];
			BuildDataList();
			//DataList["txt_search"] = DataList;
			
            $("input").on("keypress", function () {			
				//populate($(this).data());
				populate2();
            });
			
			$("select").on("change", function() {	
				DataList = [];
				BuildDataList();
				//DataList["txt_search"] = DataList;
				//populate($(this).data());	
				populate2();
			});
			
			function populate(data)
			{
				var element = $('#' + data.listid);
				var items = DataList[data.list];
				var appendTo = $( ".selector" ).autocomplete( "option", "appendTo" );
				
				element.find('option').remove().end();
				
				$.each(items, function (index, value) 
				{
					element.append('<option value = "' + value + '"/>');
				});
				
				$( ".selector" ).autocomplete( "option", "appendTo", "#search" );
			}
			
			$( function populate2 () 
			{
				$( "#txt_search" ).autocomplete({ source: DataList});
			} );
			
			function BuildDataList() {
				$.ajax({
					type: "GET",
					async: false,
					//url: "XML_F52E2B61-18A1-11d1-B105-00805F49916B13.xml",
					url: "XML_F52E2B61-18A1-11d1-B105-00805F49916B2-new.xml",
					cache: false,
					dataType: "xml",
					success: function(xml) {
						 var filter = $('#filter :selected').text();				 
						 					 
						 switch (filter)
						 {
							 case "All":
								//Design And Construction
								DataList.push("Design And Construction");
								$(xml).find('DesignAndConstruction Product').each(function()
								 {
									 var name
									 var code
									 var description							 
									 
									//Add Product Names To List								 
									$(this).find("prd_name").each(function(){
										//var name = $(this).text();	
										name = $(this).text();										
										 //DataList.push(String(name));											
									});
									
									//Add Product Codes To List
									$(this).find("prd_code").each(function(){
										//var code = $(this).text();	
										code = $(this).text();
										 //DataList.push(String(code));
									});
									
									//Add Product Descriptions To List
									$(this).find("prd_description").each(function(){
										//var description = $(this).text();	
										description = $(this).text();	
										 //DataList.push(String(description));
									});								
									
									DataList.push("Product Name: " + name);
									DataList.push("Product Code: " + code);
									DataList.push("Product Description: " + description);
									DataList.push(String("==="));
								});
								
								//Environmental Services
								DataList.push("Environmental Services");
								$(xml).find('EnvironmentalServices Product').each(function()
								 {
									//Add Product Names To List								 
									$(this).find("prd_name").each(function(){
										var name = $(this).text();				
										 DataList.push(String(name));
									});
									
									//Add Product Codes To List
									$(this).find("prd_code").each(function(){
										var code = $(this).text();				
										 DataList.push(String(code));
									});
									
									//Add Product Descriptions To List
									$(this).find("prd_description").each(function(){
										var description = $(this).text();				
										 DataList.push(String(description));
									});
								});
								
								//Coding And Billing
								$(xml).find('CodingAndBilling Product').each(function()
								 {
									//Add Product Names To List								 
									$(this).find("prd_name").each(function(){
										var name = $(this).text();				
										 DataList.push(String(name));											 
									});
									
									//Add Product Codes To List
									$(this).find("prd_code").each(function(){
										var code = $(this).text();				
										 DataList.push(String(code));
									});
									
									//Add Product Descriptions To List
									$(this).find("prd_description").each(function(){
										var description = $(this).text();				
										 DataList.push(String(description));
									});
								});
								break;
							default:
								alert("No Products Available Currently!");
							break;
						 }	
					}
				});
			}
		});

我之前说过的原始XML效果很好,但现在他们想读取该属性。这是有效的原始XML代码段:

旧XML SNippet:

<Products>
  <EnvironmentalServices>
    <Product>
      <prd_code>057034</prd_code>
      <prd_name>Practice Guidance for Healthcare Environmental Cleaning, Second Edition (Print Format)</prd_name>
      <prd_description>This publication, prepared by AHE and edited by infection control professionals contains the recommended practices for environmental cleaning in healthcare facilities.</prd_description>
    </Product>
  </EnvironmentalServices>
  <PlanningandStrategy>
    <Product>
      <prd_code>055577</prd_code>
      <prd_name>Operating Room HVAC Setback Strategies  </prd_name>
      <prd_description>Operating room setback is a proven energy-saving strategy for hospitals and ambulatory surgery centers. This paper presents possibilities and question to ask to determine a facility's approach.</prd_description>
    </Product>
  </PlanningandStrategy>
  <FacilitiesManagement>
    <Product>
      <prd_code>055593</prd_code>
      <prd_name>Promoting the Value of the Facility Department to the C-Suite </prd_name>
      <prd_description>This monograph presents strategies facility professionals can use to develop relationships with hospital leaders and show the value of their work. The monograph includes real-world examples of facility professionals who have successfully shown the value of their departments to organizational leaders.</prd_description>
    </Product>
  </FacilitiesManagement>
  <DesignandConstruction>
    <Product>
      <prd_code>055373</prd_code>
      <prd_name>2010 FGI Guidelines for Design and Construction of Health Care Facilities - Book Format</prd_name>
      <prd_description>The Guidelines provides minimum program, space and design needs for clinical and support areas of hospitals, nursing facilities, psychiatric facilities, outpatient, rehabilitation, and long-term care facilities.</prd_description>
    </Product>
  </DesignandConstruction>
</Products>

请记住,这只是一个片段。无论如何,我需要帮助的部分是循环阅读XML文档。因此,我只需要帮助调整此部分以通过属性读取新的XML:

//Data Products
								$(xml).find('DataProducts Product').each(function()
								 {
									//Add Product Names To List								 
									$(this).find("prd_name").each(function(){
										var name = $(this).text();				
										 DataList.push(String(name));
									});
									
									//Add Product Codes To List
									$(this).find("prd_code").each(function(){
										var code = $(this).text();				
										 DataList.push(String(code));
									});
									
									//Add Product Descriptions To List
									$(this).find("prd_description").each(function(){
										var description = $(this).text();				
										 DataList.push(String(description));
									});
								});

编辑: 只是基于Ryans Post的猜测。我现在无法测试,等待在Visual Studio上完成自我修复。

var name = $(xml).getElementsByTagName("PRODUCT");
								 
   for(var j = 0; j < names.length; j++) 
   {
    console.log(names[j].getAttribute("Leadership and Governance"));

    If(names[j].getAttribute("Leadership and Governance") == "Leadership and Governance")
    {										
      //Add Product Names To List								 
      $(this).find("prd_name").each(function(){
        var name = $(this).text();				
         DataList.push(String(name));
      });
    }
 }

编辑: 我试过了,但是没有用。我要关闭吗?

$(xml).find('PRODUCT[Category=Leadership and Governance]').each(function ()
{
    //Add Product Names To List								 
    $(this).find("prd_name").each(function () {
        var name = $(this).text();
        DataList.push(String(name));
    });
});

1 个答案:

答案 0 :(得分:0)

我将对此做进一步测试,但我认为我有解决方案:

var Category = "Leadership and Governance";

$(xml).find('PRODUCT[Category="' + Category + '"]').each(function ()
{
    $(this).find("prd_name").each(function () {
        var name = $(this).text();
        console.log(String(name));
        DataList.push(name);
    });
});