Parse XML and display it in Activity

Parse the XML and display it in the Activity, the format is as follows:

<xml>
<userLoginName>用户登录名</userLoginName>
<password>用户密码</password>
<requestType>请求类型</ requestType >
<randomKey>随机字符串</ randomKey >
<params>
<item>参数 1</item>
<item>参数 2</item>
</params>
</xml>

To parse XML and display it in an Activity, you can use the XML parser provided by Android. Here is a simple sample code that demonstrates how to parse the above XML and display it in an Activity:

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class MainActivity extends AppCompatActivity {

    private TextView userLoginNameTextView;
    private TextView passwordTextView;
    private TextView requestTypeTextView;
    private TextView randomKeyTextView;
    private TextView paramsTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化TextView
        userLoginNameTextView = findViewById(R.id.userLoginNameTextView);
        passwordTextView = findViewById(R.id.passwordTextView);
        requestTypeTextView = findViewById(R.id.requestTypeTextView);
        randomKeyTextView = findViewById(R.id.randomKeyTextView);
        paramsTextView = findViewById(R.id.paramsTextView);

        // 解析XML
        try {
            // 从资源文件中获取XML内容
            String xmlString = getString(R.string.xml_content);

            // 创建DOM解析器工厂对象
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            // 解析XML字符串为Document对象
            Document doc = builder.parse(new InputSource(new StringReader(xmlString)));

            // 获取根元素
            Element rootElement = doc.getDocumentElement();

            // 获取子元素的值并显示到TextView中
            userLoginNameTextView.setText(getTagValue(rootElement, "userLoginName"));
            passwordTextView.setText(getTagValue(rootElement, "password"));
            requestTypeTextView.setText(getTagValue(rootElement, "requestType"));
            randomKeyTextView.setText(getTagValue(rootElement, "randomKey"));

            // 处理params节点下的item子节点
            StringBuilder paramsBuilder = new StringBuilder();
            NodeList paramsList = rootElement.getElementsByTagName("params").item(0).getChildNodes();
            for (int i = 0; i < paramsList.getLength(); i++) {
                Node itemNode = paramsList.item(i);
                if (itemNode.getNodeType() == Node.ELEMENT_NODE) {
                    String itemValue = itemNode.getTextContent();
                    paramsBuilder.append(itemValue).append("\n");
                }
            }
            paramsTextView.setText(paramsBuilder.toString());

        } catch (Exception e) {
            Log.e("XML Parsing", "Error: " + e.getMessage());
        }
    }

    // 获取指定标签的值
    private String getTagValue(Element element, String tagName) {
        NodeList nodeList = element.getElementsByTagName(tagName).item(0).getChildNodes();
        Node node = nodeList.item(0);
        return node.getNodeValue();
    }
}

Note that the above sample code assumes that you res/values/strings.xmlhave defined xml_contenta string resource named in the file that contains the XML content to be parsed. Make sure the correct XML content is defined in the resource file before XML parsing.

In the Activity layout file (activity_main.xml), you need to define the corresponding TextView control to display the parsed data, for example:

<TextView
    android:id="@+id/userLoginNameTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="User Login Name: " />

<TextView
    android:id="@+id/passwordTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Password: " />

<TextView
    android:id="@+id/requestTypeTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Request Type: " />

<TextView
    android:id="@+id/randomKeyTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Random Key: " />

<TextView
    android:id="@+id/paramsTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Params: " />

In this way, the parsed XML data will be displayed in the corresponding TextView. Remember to make appropriate layout and UI adjustments according to your actual situation.

Guess you like

Origin blog.csdn.net/m0_52537869/article/details/131094907