xml.每个标记的DocumentElement

本文关键字:DocumentElement xml | 更新日期: 2023-09-27 17:59:05

我试图让我的代码读取每个标记和值,但在试图弄清楚它时遇到了困难。

这是我的数据:

<?xml version="1.0" encoding="utf-8"?>
<Word1>Trying</Word1>
<Word2>To</Word2>
<Word3>Learn</Word3>

我希望输出是这样的:

Word1 => Trying
Word2 => To
Word3 => Learn

xml.每个标记的DocumentElement

这不是有效的XML。一个XML文档中只能有一个根元素。

因此,输入应该是这样的:

<?xml version="1.0" encoding="utf-8"?>
<Words>
  <Word1>Trying</Word1>
  <Word2>To</Word2>
  <Word3>Learn</Word3>
</Words>

您可以在C#中以多种方式对此进行解析。两种常见的方法是使用XmlDocument或使用"LINQ to XML"中的XDocument,然后在每个元素上循环或通过名称或XPath读取它们。这是一个相当宽泛的主题,但我想你之所以被困在这里,只是因为你想拥有多个根元素(这也是不可能的)。

试试这个

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string input =
             "<?xml version='"1.0'" encoding='"utf-8'"?>" +
             "<Root>" +
                "<Word1>Trying</Word1>" +
                "<Word2>To</Word2>" +
                "<Word3>Learn</Word3>" +
             "</Root>";
            XDocument doc = XDocument.Parse(input);
            var results = doc.Descendants("Root").Select(x => new {
                word1 = x.Element("Word1").Value,
                word2 = x.Element("Word2").Value,
                word3 = x.Element("Word3").Value
            }).FirstOrDefault();
        }
    }
}
​