如何在C#中读取xml数据

时间:2022-09-02 15:25:12

I'm trying to read an xml and display its data in a form. Following is the code generated with the form. If I want to just display "Hello World" from a tab value in XML, where should I put the code in the C# code generated by the VB form, if my Xml schema (test.xml)is as below.

我正在尝试读取xml并在表单中显示其数据。以下是使用表单生成的代码。如果我只想从XML中的选项卡值显示“Hello World”,那么我应该将代码放在VB表单生成的C#代码中,如果我的Xml架构(test.xml)如下所示。

   <tab>
        <message>Hello World</Message>
   </tab>

Following is the code generated by the form. I included System.Xml to read the Xml file. Any help is greatly appreciated. Thank you

以下是表单生成的代码。我包括System.Xml来读取Xml文件。任何帮助是极大的赞赏。谢谢

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace xmldatatest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("C:\\test.xml");
        }
     }
 }

2 个解决方案

#1


1  

Correct your XML File to be valid:

更正您的XML文件是有效的:

<?xml version="1.0" encoding="utf-8" ?>
<tab>
    <message>Hello World</message>
</tab>

C# code should be like:

C#代码应该是这样的:

public partial class Form1 : Form
{
    public Form1()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("C:\\test.xml");

        var node = doc.SelectSingleNode("/tab/message");

        // Gets "Hello World"
        var message = node.InnerText;

        // you can do whatever with the message now...
    }
}

#2


0  

The XML example you supplied is not valid:

您提供的XML示例无效:

<tab>
     <message>Hello World</Message>
</tab>

Your message tag starts with this <message> but ends with this </Message>.

您的消息标记以此 开头,但以此 结束。

#1


1  

Correct your XML File to be valid:

更正您的XML文件是有效的:

<?xml version="1.0" encoding="utf-8" ?>
<tab>
    <message>Hello World</message>
</tab>

C# code should be like:

C#代码应该是这样的:

public partial class Form1 : Form
{
    public Form1()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("C:\\test.xml");

        var node = doc.SelectSingleNode("/tab/message");

        // Gets "Hello World"
        var message = node.InnerText;

        // you can do whatever with the message now...
    }
}

#2


0  

The XML example you supplied is not valid:

您提供的XML示例无效:

<tab>
     <message>Hello World</Message>
</tab>

Your message tag starts with this <message> but ends with this </Message>.

您的消息标记以此 开头,但以此 结束。