Nodejs truy vấn XML

XPath sử dụng biểu thức đường dẫn để điều hướng trong tài liệu XML

  • XPath chứa một thư viện các hàm tiêu chuẩn
  • XPath là một thành phần chính trong XSLT và trong XQuery
  • XPath là một khuyến nghị của W3C

  • Biểu thức đường dẫn XPath

    XPath sử dụng các biểu thức đường dẫn để chọn các nút hoặc tập hợp nút trong tài liệu XML. Các biểu thức đường dẫn này trông rất giống các biểu thức bạn thấy khi làm việc với hệ thống tệp máy tính truyền thống

    Các biểu thức XPath có thể được sử dụng trong JavaScript, Java, Lược đồ XML, PHP, Python, C và C++ và nhiều ngôn ngữ khác

    Vì rất nhiều phản hồi API ở dạng XML, chúng tôi sẽ xem xét phân tích cú pháp XML trong Node. js để giúp bạn truy cập dữ liệu thú vị nhanh hơn

    Hướng dẫn này giả định rằng bạn đã xem qua Node của chúng tôi. js bắt đầu hướng dẫn và làm quen với cách Node của chúng tôi. SDK js hoạt động

    Nút không bao gồm bất kỳ khả năng phân tích cú pháp XML nào trong thư viện chuẩn của nó. Ví dụ này sử dụng Node ElementTree, một triển khai Node của thư viện Python XML phổ biến. Nó có thể được cài đặt bằng Trình quản lý gói Node, bằng cách chạy lệnh sau trong thư mục chứa thư mục node_modules với SDK Temboo đã giải nén

    npm install elementtree
    

    Nhận phản hồi XML

    1 Đăng nhập vào Temboo và truy cập Yahoo > Thời tiết > GetWeatherByAddress Choreo trong Thư viện của chúng tôi

    2 Nhập một vị trí vào phần nhập Địa chỉ và nhấp vào Tạo mã để kiểm tra Vũ đạo từ trang web của chúng tôi

    3 Bạn nhận được cả đống XML trong kết quả Phản hồi với nhiều thông tin liên quan đến thời tiết về vị trí. Tiếp theo chúng ta sẽ xem cách phân tích phản hồi này trong Node. js và chỉ chọn ra những phần chúng tôi quan tâm

    Phân tích nó trong Node. js

    4 Tạo một nút mới. js và sao chép mã bên dưới. Bước 5 & 6 hướng dẫn bạn về những gì xảy ra trong mã

    var et = require("elementtree");
    var tsession = require("temboo/core/temboosession");
    var Yahoo = require("temboo/Library/Yahoo/Weather");
    
    var session = new tsession.TembooSession("ACCOUNT_NAME", "APP_NAME", "APP_KEY");
    var getWeatherByAddressChoreo = new Yahoo.GetWeatherByAddress(session);
    
    // Instantiate and populate the input set for the choreo
    var getWeatherByAddressInputs = getWeatherByAddressChoreo.newInputSet();
    
    // Set inputs
    getWeatherByAddressInputs.set_Address("104 Franklin St, New York, NY");
    
    // Run the choreo; on success parse XML response and report key info.
    getWeatherByAddressChoreo.execute(
        getWeatherByAddressInputs,
        function(results) {
            var xmlData = et.parse(results.get_Response());
            var condition = xmlData.find("channel/item/yweather:condition");
            var temp = condition.attrib.temp;
            var text = condition.attrib.text;
            console.log("The weather is %s with a temperature of %s.", text, temp);
        },
        // On failure, log errors returned by Temboo.
        function(error) {
            console.log(error.type); 
            console.log(error.message);
        }
    );
    

    5 Trước tiên, chúng tôi phải chuyển đổi phản hồi XML từ Yahoo sang w3c. đối tượng tài liệu

    6 Tiếp theo, chúng ta cần phân tích dữ liệu chúng ta muốn từ tệp XML. Nó giúp xem xét cấu trúc của tệp XML để có ý tưởng về cách nó được tổ chức. Chúng tôi muốn các thuộc tính văn bản và tạm thời. Bạn có thể tìm thấy chúng trong.
    ______21.

    7Vậy thôi. Bạn có thể chạy mã trong Nút của mình. js IDE để dùng thử. Bạn sẽ thấy văn bản điều kiện thời tiết và nhiệt độ được in trong bảng điều khiển

    Tiếp theo là gì?

    Bây giờ bạn đã sẵn sàng xử lý tất cả các loại nhiệm vụ phân tích cú pháp XML trong Node. js. Bạn có thể tìm thấy rất nhiều XML để chơi trong Thư viện hơn 2000 Công việc của chúng tôi

    Khi bạn đã thiết lập và chạy mã của mình, bạn đã sẵn sàng tiếp tục và làm nhiều việc hơn. Từ việc theo dõi các ứng dụng đang chạy của bạn, đến việc di chuyển mã Temboo đã tạo sang môi trường phát triển ưa thích của bạn và chia sẻ nó với đồng nghiệp, cộng tác viên và bạn bè - chúng tôi đã hỗ trợ bạn

    Để lấy tất cả các tệp cũ hơn một giờ và xóa chúng, chúng ta có thể sử dụng

    fs = require('fs');
    const parser = require('xml2json');
    fs.readFile('./data.xml', (err, data) => {
    const json = parser.toJson(data);
    console.log(json);
    });
    1 để lấy các tệp trong thư mục

    Sau đó, chúng tôi có thể sử dụng

    fs = require('fs');
    const parser = require('xml2json');
    fs.readFile('./data.xml', (err, data) => {
    const json = parser.toJson(data);
    console.log(json);
    });
    2 để lấy thời gian và chúng tôi có thể sử dụng thời gian đó để so sánh với thời gian hiện tại để xem liệu một giờ đã trôi qua kể từ khi tệp được tạo chưa

    Khi tệp được tạo một giờ trước hoặc sớm hơn, chúng tôi có thể sử dụng

    fs = require('fs');
    const parser = require('xml2json');
    fs.readFile('./data.xml', (err, data) => {
    const json = parser.toJson(data);
    console.log(json);
    });
    3 để xóa nó

    Chẳng hạn, chúng ta có thể viết

    const uploadsDir = path.join( __dirname, '/uploads');fs.readdir(uploadsDir, (err, files) => {
    files.forEach((file, index) => {
    fs.stat(path.join(uploadsDir, file), (err, stat) => {
    let endTime, now;
    if (err) {
    return console.error(err);
    }
    now = new Date().getTime();
    endTime = new Date(stat.ctime).getTime() + 3600000;
    if (now > endTime) {
    return rimraf(path.join(uploadsDir, file), (err) => {
    if (err) {
    return console.error(err);
    }
    console.log('successfully deleted');
    });
    }
    });
    });
    });

    Chúng tôi đọc thư mục với

    fs = require('fs');
    const parser = require('xml2json');
    fs.readFile('./data.xml', (err, data) => {
    const json = parser.toJson(data);
    console.log(json);
    });
    1

    Sau đó, chúng tôi lặp lại

    fs = require('fs');
    const parser = require('xml2json');
    fs.readFile('./data.xml', (err, data) => {
    const json = parser.toJson(data);
    console.log(json);
    });
    5 thu được trong cuộc gọi lại

    Sau đó, chúng tôi gọi

    fs = require('fs');
    const parser = require('xml2json');
    fs.readFile('./data.xml', (err, data) => {
    const json = parser.toJson(data);
    console.log(json);
    });
    2 để lấy thông tin tệp

    Chúng tôi sử dụng thuộc tính

    fs = require('fs');
    const parser = require('xml2json');
    fs.readFile('./data.xml', (err, data) => {
    const json = parser.toJson(data);
    console.log(json);
    });
    7 để lấy thời gian khi tệp được tạo

    Sau đó, chúng tôi sử dụng

    fs = require('fs');
    const parser = require('xml2json');
    fs.readFile('./data.xml', (err, data) => {
    const json = parser.toJson(data);
    console.log(json);
    });
    8 để biến nó thành dấu thời gian

    Và chúng tôi thêm 3600000 là một giờ tính bằng mili giây

    Sau đó, nếu

    fs = require('fs');
    const parser = require('xml2json');
    fs.readFile('./data.xml', (err, data) => {
    const json = parser.toJson(data);
    console.log(json);
    });
    9 là
    var et = require("elementtree");
    var tsession = require("temboo/core/temboosession");
    var Yahoo = require("temboo/Library/Yahoo/Weather");
    
    var session = new tsession.TembooSession("ACCOUNT_NAME", "APP_NAME", "APP_KEY");
    var getWeatherByAddressChoreo = new Yahoo.GetWeatherByAddress(session);
    
    // Instantiate and populate the input set for the choreo
    var getWeatherByAddressInputs = getWeatherByAddressChoreo.newInputSet();
    
    // Set inputs
    getWeatherByAddressInputs.set_Address("104 Franklin St, New York, NY");
    
    // Run the choreo; on success parse XML response and report key info.
    getWeatherByAddressChoreo.execute(
        getWeatherByAddressInputs,
        function(results) {
            var xmlData = et.parse(results.get_Response());
            var condition = xmlData.find("channel/item/yweather:condition");
            var temp = condition.attrib.temp;
            var text = condition.attrib.text;
            console.log("The weather is %s with a temperature of %s.", text, temp);
        },
        // On failure, log errors returned by Temboo.
        function(error) {
            console.log(error.type); 
            console.log(error.message);
        }
    );
    
    20 , chúng tôi biết rằng đã hơn một giờ trôi qua kể từ khi tệp được tạo

    Sau đó, chúng tôi có thể sử dụng

    fs = require('fs');
    const parser = require('xml2json');
    fs.readFile('./data.xml', (err, data) => {
    const json = parser.toJson(data);
    console.log(json);
    });
    3 để xóa tệp

    Chúng tôi sử dụng đường dẫn đầy đủ

    Gọi một Dịch vụ Web bằng Node. js

    Chúng tôi có thể gọi một máy chủ web trong ứng dụng Node bằng cách thực hiện các yêu cầu HTTP như chúng tôi thực hiện ở phía máy khách

    Chẳng hạn, chúng ta có thể viết

    var et = require("elementtree");
    var tsession = require("temboo/core/temboosession");
    var Yahoo = require("temboo/Library/Yahoo/Weather");
    
    var session = new tsession.TembooSession("ACCOUNT_NAME", "APP_NAME", "APP_KEY");
    var getWeatherByAddressChoreo = new Yahoo.GetWeatherByAddress(session);
    
    // Instantiate and populate the input set for the choreo
    var getWeatherByAddressInputs = getWeatherByAddressChoreo.newInputSet();
    
    // Set inputs
    getWeatherByAddressInputs.set_Address("104 Franklin St, New York, NY");
    
    // Run the choreo; on success parse XML response and report key info.
    getWeatherByAddressChoreo.execute(
        getWeatherByAddressInputs,
        function(results) {
            var xmlData = et.parse(results.get_Response());
            var condition = xmlData.find("channel/item/yweather:condition");
            var temp = condition.attrib.temp;
            var text = condition.attrib.text;
            console.log("The weather is %s with a temperature of %s.", text, temp);
        },
        // On failure, log errors returned by Temboo.
        function(error) {
            console.log(error.type); 
            console.log(error.message);
        }
    );
    
    4

    Chúng tôi sử dụng phương pháp

    var et = require("elementtree");
    var tsession = require("temboo/core/temboosession");
    var Yahoo = require("temboo/Library/Yahoo/Weather");
    
    var session = new tsession.TembooSession("ACCOUNT_NAME", "APP_NAME", "APP_KEY");
    var getWeatherByAddressChoreo = new Yahoo.GetWeatherByAddress(session);
    
    // Instantiate and populate the input set for the choreo
    var getWeatherByAddressInputs = getWeatherByAddressChoreo.newInputSet();
    
    // Set inputs
    getWeatherByAddressInputs.set_Address("104 Franklin St, New York, NY");
    
    // Run the choreo; on success parse XML response and report key info.
    getWeatherByAddressChoreo.execute(
        getWeatherByAddressInputs,
        function(results) {
            var xmlData = et.parse(results.get_Response());
            var condition = xmlData.find("channel/item/yweather:condition");
            var temp = condition.attrib.temp;
            var text = condition.attrib.text;
            console.log("The weather is %s with a temperature of %s.", text, temp);
        },
        // On failure, log errors returned by Temboo.
        function(error) {
            console.log(error.type); 
            console.log(error.message);
        }
    );
    
    22 để đưa ra yêu cầu

    Chúng tôi gọi

    var et = require("elementtree");
    var tsession = require("temboo/core/temboosession");
    var Yahoo = require("temboo/Library/Yahoo/Weather");
    
    var session = new tsession.TembooSession("ACCOUNT_NAME", "APP_NAME", "APP_KEY");
    var getWeatherByAddressChoreo = new Yahoo.GetWeatherByAddress(session);
    
    // Instantiate and populate the input set for the choreo
    var getWeatherByAddressInputs = getWeatherByAddressChoreo.newInputSet();
    
    // Set inputs
    getWeatherByAddressInputs.set_Address("104 Franklin St, New York, NY");
    
    // Run the choreo; on success parse XML response and report key info.
    getWeatherByAddressChoreo.execute(
        getWeatherByAddressInputs,
        function(results) {
            var xmlData = et.parse(results.get_Response());
            var condition = xmlData.find("channel/item/yweather:condition");
            var temp = condition.attrib.temp;
            var text = condition.attrib.text;
            console.log("The weather is %s with a temperature of %s.", text, temp);
        },
        // On failure, log errors returned by Temboo.
        function(error) {
            console.log(error.type); 
            console.log(error.message);
        }
    );
    
    23 để thực hiện yêu cầu với cơ thể

    Đối tượng

    var et = require("elementtree");
    var tsession = require("temboo/core/temboosession");
    var Yahoo = require("temboo/Library/Yahoo/Weather");
    
    var session = new tsession.TembooSession("ACCOUNT_NAME", "APP_NAME", "APP_KEY");
    var getWeatherByAddressChoreo = new Yahoo.GetWeatherByAddress(session);
    
    // Instantiate and populate the input set for the choreo
    var getWeatherByAddressInputs = getWeatherByAddressChoreo.newInputSet();
    
    // Set inputs
    getWeatherByAddressInputs.set_Address("104 Franklin St, New York, NY");
    
    // Run the choreo; on success parse XML response and report key info.
    getWeatherByAddressChoreo.execute(
        getWeatherByAddressInputs,
        function(results) {
            var xmlData = et.parse(results.get_Response());
            var condition = xmlData.find("channel/item/yweather:condition");
            var temp = condition.attrib.temp;
            var text = condition.attrib.text;
            console.log("The weather is %s with a temperature of %s.", text, temp);
        },
        // On failure, log errors returned by Temboo.
        function(error) {
            console.log(error.type); 
            console.log(error.message);
        }
    );
    
    24 có tiêu đề, tên máy chủ và phương thức yêu cầu

    Khi yêu cầu kết thúc, cuộc gọi lại được gọi và

    var et = require("elementtree");
    var tsession = require("temboo/core/temboosession");
    var Yahoo = require("temboo/Library/Yahoo/Weather");
    
    var session = new tsession.TembooSession("ACCOUNT_NAME", "APP_NAME", "APP_KEY");
    var getWeatherByAddressChoreo = new Yahoo.GetWeatherByAddress(session);
    
    // Instantiate and populate the input set for the choreo
    var getWeatherByAddressInputs = getWeatherByAddressChoreo.newInputSet();
    
    // Set inputs
    getWeatherByAddressInputs.set_Address("104 Franklin St, New York, NY");
    
    // Run the choreo; on success parse XML response and report key info.
    getWeatherByAddressChoreo.execute(
        getWeatherByAddressInputs,
        function(results) {
            var xmlData = et.parse(results.get_Response());
            var condition = xmlData.find("channel/item/yweather:condition");
            var temp = condition.attrib.temp;
            var text = condition.attrib.text;
            console.log("The weather is %s with a temperature of %s.", text, temp);
        },
        // On failure, log errors returned by Temboo.
        function(error) {
            console.log(error.type); 
            console.log(error.message);
        }
    );
    
    25 có luồng với phản hồi

    Chúng tôi lắng nghe sự kiện

    var et = require("elementtree");
    var tsession = require("temboo/core/temboosession");
    var Yahoo = require("temboo/Library/Yahoo/Weather");
    
    var session = new tsession.TembooSession("ACCOUNT_NAME", "APP_NAME", "APP_KEY");
    var getWeatherByAddressChoreo = new Yahoo.GetWeatherByAddress(session);
    
    // Instantiate and populate the input set for the choreo
    var getWeatherByAddressInputs = getWeatherByAddressChoreo.newInputSet();
    
    // Set inputs
    getWeatherByAddressInputs.set_Address("104 Franklin St, New York, NY");
    
    // Run the choreo; on success parse XML response and report key info.
    getWeatherByAddressChoreo.execute(
        getWeatherByAddressInputs,
        function(results) {
            var xmlData = et.parse(results.get_Response());
            var condition = xmlData.find("channel/item/yweather:condition");
            var temp = condition.attrib.temp;
            var text = condition.attrib.text;
            console.log("The weather is %s with a temperature of %s.", text, temp);
        },
        // On failure, log errors returned by Temboo.
        function(error) {
            console.log(error.type); 
            console.log(error.message);
        }
    );
    
    95 để lấy các khối dữ liệu và nối với chuỗi
    var et = require("elementtree");
    var tsession = require("temboo/core/temboosession");
    var Yahoo = require("temboo/Library/Yahoo/Weather");
    
    var session = new tsession.TembooSession("ACCOUNT_NAME", "APP_NAME", "APP_KEY");
    var getWeatherByAddressChoreo = new Yahoo.GetWeatherByAddress(session);
    
    // Instantiate and populate the input set for the choreo
    var getWeatherByAddressInputs = getWeatherByAddressChoreo.newInputSet();
    
    // Set inputs
    getWeatherByAddressInputs.set_Address("104 Franklin St, New York, NY");
    
    // Run the choreo; on success parse XML response and report key info.
    getWeatherByAddressChoreo.execute(
        getWeatherByAddressInputs,
        function(results) {
            var xmlData = et.parse(results.get_Response());
            var condition = xmlData.find("channel/item/yweather:condition");
            var temp = condition.attrib.temp;
            var text = condition.attrib.text;
            console.log("The weather is %s with a temperature of %s.", text, temp);
        },
        // On failure, log errors returned by Temboo.
        function(error) {
            console.log(error.type); 
            console.log(error.message);
        }
    );
    
    27

    Làm cách nào để phân tích cú pháp XML bằng NodeJS?

    Tạo ứng dụng NodeJS, Express . Lệnh này sẽ tạo một ứng dụng cấp tốc có tên là nodejs-parse-xml. Nhập lệnh cd nodejs-parse-xml. Nhập npm install để cài đặt các phụ thuộc và mô-đun. Open command prompt and type following command to generate a NodeJS, Express application. This command will generate an express application named nodejs-parse-xml. Type command cd nodejs-parse-xml. Type npm install to install the dependencies and modules.

    Làm cách nào để lấy giá trị từ XML trong nút js?

    Để truy xuất giá trị văn bản của phần tử, bạn phải truy xuất giá trị nút văn bản của phần tử. .
    Phương thức getElementsByTagName. .
    Thuộc tính ChildNodes. .
    Thuộc tính nodeValue. .
    Nhận một giá trị thuộc tính - getAttribute().
    Nhận một giá trị thuộc tính - getAttributeNode()

    Làm cách nào để đọc và ghi tệp XML trong NodeJS?

    Chuyển đổi sang XML và ghi vào FIle . readFile("test. xml", "utf-8", function(err, data) { if (err) console. log(err); // chúng tôi đăng xuất bảng điều khiển kết quả readFile. nhật ký (dữ liệu); .

    Làm cách nào để gửi phản hồi XML trong nút js?

    Cách tạo yêu cầu nhanh và nhận phản hồi XML trong nút .
    Bước 1. Tạo thư mục mới
    Bước 2. Chạy Npm Init
    Bước 3. Thêm các mô-đun XML và Express
    Bước 4. Thiết lập máy chủ Nodemon
    Bước 5. Nhận phản hồi XML
    Bước 6. Bắt đầu ứng dụng nút