我有以下XML:
<Books>
<Title>Book 1</Title>
<Author>A</Author>
</Books>
<Books>
<Title>Book 2</Title>
<Author>B</Author>
</Books>
输出:
<Books>
<Title>Book 1</Title>
<Author>A</Author>
<Title>Book 2</Title>
<Author>B</Author>
</Books>
我想用C#编写结果作为输出,我该怎么办?
答案 0 :(得分:1)
创建此类:
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
[XmlRoot(ElementName="Books")]
public class Books {
[XmlElement(ElementName="Title")]
public List<string> Title { get; set; }
[XmlElement(ElementName="Author")]
public List<string> Author { get; set; }
}
}
解析您的XML
但是你的XML并没有很好地形成。 我推荐这样的东西:
<Books>
<Book>
<Title>Book 1</Title>
<Author>A</Author>
</Book>
<Book>
<Title>Book 2</Title>
<Author>B</Author>
</Book>
</Books>
答案 1 :(得分:0)
在此示例中,newDoc
将包含您想要的内容
var xml = @"
<xml>
<Books>
<Title>Book 1</Title>
<Author>A</Author>
</Books>
<Books>
<Title>Book 2</Title>
<Author>B</Author>
</Books>
</xml>";
var originalElements = XDocument.Parse(xml).Root.Elements("Books").Descendants();
var newDoc = new XDocument(new XElement("Books", originalElements));