Example code details for XML-based shopping cart
Shopping carts are an indispensable part of e-commerce websites, but currently most shopping carts can only be used as a display for products selected by a customer. The client cannot extract the contents of the shopping cart to meet its own transaction processing needs. This is necessary in some e-commerce activities. The emergence of xml makes the data transmitted on the network meaningful. We can display the contents of a shopping cart in different styles according to different requirements.
This article will analyze in detail an XML-based shopping cart implemented in java. The following is the XML internal structure of a shopping cart containing five items: its root element is cart, the total element represents the total amount in the shopping cart, each item element represents a product, and the sub-elements in the item are marked respectively. The specific information of the product can be added, modified or deleted according to the actual situation.
Here, you need to create a class that represents the shopping cart: XMLCart.java. It is a JavaBean, so it contains an empty constructor. This class contains some basic functions of the shopping cart: generating an empty shopping cart, adding items to the shopping cart, deleting items in the shopping cart, changing the number of items in the shopping cart, clearing the shopping cart, etc. It has a global private variable "PRivate XMLDocument myCart". myCart is used to store the detailed contents of the shopping cart. The basic function of the shopping cart is to operate it. Its type is XMLDocument, which is an XML document. In this way, the operation of the shopping cart is converted into the addition and deletion of sub-elements in myCart, and the calculation and modification of element values.
1. Clear shopping cart
Clearing the shopping cart will generate an empty shopping cart. The empty shopping cart here is an XML document containing the root element cart and its element total. The total element is the total amount of the shopping cart. Its initial value is 0. Its specific XML form is as follows:
< ?xml version=‘1.0’ encoding=‘gb2312’?> < cart> < total>0< /total> < /cart>
Convert this XML The string is converted into XMLDocument by the parseString function and stored in myCart.
The code is as follows:
public void emptyCart() throws IOException,SAXException{ String stringCart=“< ?xml version=‘1.0’encoding=‘gb2312’?> ”+ “< cart>< total>0< /total>< /cart>”; myCart=parseString(stringCart); }
2. Add a product
Add a product, that is, add the incoming item element to the root element cart,
The item includes product details,
and calculate the value of total at the same time. The code is as follows:
public void addItemToCart(String stringItem) throws IOException,SAXException{ //将item由String转换为XMLDocument XMLDocument itemAdded=parseString(stringItem); //取出item节点,并复制它 NodeList itemList=itemAdded.getElementsByTagName(“item”); Node item=itemList.item(0); Node cloneItem=item.cloneNode(true); //如果购物车为空,则构造一个新的购物车 if(isCartEmpty()){ myCart.emptyCart(); } //如果该商品不在购物车中,则插入该商品,并计算总金额 if(!isItemExist(item,myCart)){ //取myCart的根元素,并将复制的item节点添加到后面 Element cartRoot=myCart.getDocumentElement(); Node cartNode=cartRoot.appendChild(cloneItem); computeTotal(); //计算总金额 } }
3. Delete a product
Delete a product, that is, delete the item element
of the product from the root element cart of myCart according to the product code,
and recalculate the value of total:
public void moveItemFromCart(String id){ //取出以item为单位的节点集cartList以及根元素cartRoot NodeList cartList=myCart.getElementsByTagName(“item”); Element cartRoot=myCart.getDocumentElement(); //在cartList中查找代码为选中id的商品 for(int x=0;x< cartList.getLength();x++){ Node itemNode=cartList.item(x); String idValue=itemNode.getFirstChild(). getFirstChild().getNodeValue(); //如果找到,则从cartRoot中删除该节点,并跳出循环 if(idValue.equals(id)){ itemNode=cartRoot.removeChild(itemNode); break; } } computeTotal(); //计算总金额 }
4. Change the quantity of the product
According to the quantity filled in by the customer on the page, modify the quantity in myCart,
and recalculate the total:
public void addQuantityToCart(String qnty) throws IOException,SAXException{ //将传过来的包含商品数量的一组XML字符串转换为XML文档 XMLDocument quantityChanged=parseString(qnty); //取出包含新数量的quantity节点集和myCart中的quantity节点集 NodeList quantityList=quantityChanged.getElementsByTagName(“quantity”); NodeList cartList=myCart.getElementsByTagName(“quantity”); //循环改变商品的数量 for(int x=0;x< cartList.getLength();x++){ //将新quantity的值赋给myCart中相应的quantity中去 String quantity=quantityList.item(x).getFirstChild().getNodeValue(); cartList.item(x).getFirstChild().setNodeValue(quantity); } computeTotal(); //计算总金额 }
5. To calculate the total amount
is to calculate the value of total, where total=∑(price*quantity):
public void computeTotal(){ NodeList quantityList=myCart.getElementsByTagName(“quantity”); NodeList priceList=myCart.getElementsByTagName(“price”); float total=0; //累加总金额 for(int x=0;x< priceList.getLength();x++){ float quantity=Float.parseFloat(quantityList.item(x) .getFirstChild().getNodeValue()); float price=Float.parseFloat(priceList.item(x).getFirstChild().getNodeValue()); total=total+quantity*price; } //将total附给myCart的total String totalString=String.valueOf(total); myCart.getElementsByTagName(“total”). item(0).getFirstChild().setNodeValue(totalString); }
6. Determine whether the shopping cart is empty
Usually when adding new products, you also need to know whether the shopping cart is empty.
If it is empty, a new shopping cart must be generated.
public boolean isCartEmpty(){ //item的节点集,如果该节点集包含的节点数为0,则购物车内没有商品,返回true NodeList itemList=myCart.getElementsByTagName(“item”); if(itemList.getLength()==0) return true; else return false; }
7. Determine whether the selected product is already in the shopping cart
That is, determine whether the item of the newly transferred product already exists in myCart. If it exists, return true.
public boolean isItemExist(Node item, XMLDocument cart){ NodeList itemList=cart.getElementsByTagName(“item”); Node id=item.getFirstChild(); String idValue=id.getFirstChild().getNodeValue(); if(itemList.getLength()!=0){ for(int x=0;x< itemList.getLength();x++){ Node itemTemp = itemList.item(x); 7Node idTemp=itemTemp.getFirstChild(); String idTempValue=idTemp.getFirstChild().getNodeValue(); if(idValue.equals(idTempValue)) return true; } return false; } return false; }
In addition to the above methods, XMLCart also includes the method parseString, which converts XML strings from String to XMLDocument during input, and assigns XSL to myCart during output and returns String-type XML words. The cartTurnToStringWithXSL method of the string is used to assist in the implementation of the main operations of the shopping cart, which will not be described here.
The above is the sample code details of the XML-based shopping cart. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

How to implement a simple shopping cart function in Java? The shopping cart is an important feature of an online store, which allows users to add items they want to purchase to the shopping cart and manage the items. In Java, we can implement a simple shopping cart function by using object-oriented approach. First, we need to define a product category. This class contains attributes such as product name, price, and quantity, as well as corresponding Getter and Setter methods. For example: publicclassProduct

Python parses special characters and escape sequences in XML XML (eXtensibleMarkupLanguage) is a commonly used data exchange format used to transfer and store data between different systems. When processing XML files, you often encounter situations that contain special characters and escape sequences, which may cause parsing errors or misinterpretation of the data. Therefore, when parsing XML files using Python, we need to understand how to handle these special characters and escape sequences. 1. Special characters and

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

Practical tutorial: Detailed explanation of the shopping cart function with PHP and MySQL. The shopping cart function is one of the common functions in website development. Through the shopping cart, users can easily add the goods they want to buy to the shopping cart, and then proceed with settlement and payment. In this article, we will detail how to implement a simple shopping cart function using PHP and MySQL and provide specific code examples. To create a database and data table, you first need to create a data table in the MySQL database to store product information. The following is a simple data table

How to use Redis and JavaScript to implement the shopping cart function. The shopping cart is one of the very common functions in e-commerce websites. It allows users to add items of interest to the shopping cart, making it convenient for users to view and manage purchased items at any time. In this article, we will introduce how to implement the shopping cart function using Redis and JavaScript, and provide specific code examples. 1. Preparation Before starting, we need to ensure that Redis has been installed and configured, which can be done through the official website [https:/
