我想创建以下xml
<BookStore>
<Book>
<Name></Name>
<Author></Author>
<Price></Price>
</Book>
<Book>
<Name></Name>
<Author></Author>
<Price></Price>
</Book>
</BookStore>
来自
List<XElement> Book= xdoc.XPathSelectElements("s0:Name| s0:Author| s0:Price", namespaceManager).ToList();
我在以下地方受到打击:
XNamespace s0 = "urn:service.Bookstore.com";
XElement root=new XElement(s0 + "BookStore",
new XElement("Book",Book,
);
XDocument result = new XDocument(root);
但这使得xml结构为
<BookStore>
<Book>
<Name></Name>
<Author></Author>
<Price></Price>
<Name></Name>
<Author></Author>
<Price></Price>
</Book>
</BookStore>
请帮助我获得预期的输出。因为基本的xml结构看起来像这样
<BookStore>
<Book>
<Name></Name>
<Author></Author>
<Price></Price>
<Name></Name>
<Author></Author>
<Price></Price>
</Book>
</BookStore>
但我想把它作为
的两个独立实例答案 0 :(得分:1)
听起来你基本上需要获取元素列表并将它们分组为3个元素的组,将每个组放在Book
元素中:
// The name/author/price elements you're already getting
var elements = ...;
var groups = elements.Select((value, index) => new { value, index })
.GroupBy(pair => pair.index / 3, pair => pair.value);
XNamespace s0 = "urn:service.Bookstore.com";
XDocument result = new XDocument(new XElement(s0 + "BookStore",
groups.Select(g => new XElement("Book", g))));
答案 1 :(得分:0)
试一试:
XElement xElement = new XElement("BookStore", new XElement("Book", new XElement("Name", "value"), new XElement("Author", "value"), new XElement("Price", "value")));
xElement.Save("Location.xml");