gpt4 book ai didi

c# - 使用 XMLDocument C# xml 添加多个节点

转载 作者:数据小太阳 更新时间:2023-10-29 03:00:06 28 4
gpt4 key购买 nike

我正在尝试在我的 XML 中添加多个元素/节点(发票节点)。

这是 xml 结构:(需要输出)

<Request>
<Operation>Testing</Operation>
<Count>2</Count>
<Params>
<Invoice>
<field name="CustomerNo" value="20000" />
<field name="Email" value="test2@yahoo.com" />
<field name="Invoice" value="12345" />
</Invoice>
<Invoice>
<field name="CustomerNo" value="10000" />
<field name="Email" value="test1@yahoo.com" />
<field name="Invoice" value="54321" />
</Invoice>
</Params>
</Request>

这是我的代码

int[] invoice = new int[] {1002,1003};
foreach (int i in invoice)
{
XDocument xDocument = new XDocument(
new XDeclaration("1.0", "UTF-8", null),
new XElement("Request",
new XElement("Operation", "Testing"),
new XElement("Count","2"),
new XElement("Params",
new XElement("Invoice",
new XElement("Field",
new XAttribute("name","CustomerNo"),
new XAttribute("value","10000")),
new XElement("Field",
new XAttribute("name","Email"),
new XAttribute("value","testemail@yahoo.com")),
new XElement("Field",
new XAttribute("name","Invoice"),
new XAttribute("value",i))))));
Console.WriteLine(xDocument);
}

上面的代码生成了这个:

<Request>
<Operation>Testing</Operation>
<Count>2</Count>
<Params>
<Invoice>
<Field name="CustomerNo" value="10000" />
<Field name="Email" value="testemail@yahoo.com" />
<Field name="Invoice" value="1002" />
</Invoice>
</Params>
</Request>
<Request>
<Operation>Testing</Operation>
<Count>2</Count>
<Params>
<Invoice>
<Field name="CustomerNo" value="10000" />
<Field name="Email" value="testemail@yahoo.com" />
<Field name="Invoice" value="1003" />
</Invoice>
</Params>
</Request>

我只想根据数组中的发票数量循环发票节点部分。我知道我正在循环我的 XML 的整个结构,但我找不到将我的循环插入 XMLDocument 中的方法。

任何帮助将不胜感激!

谢谢!

最佳答案

您可以用 LINQ 替换循环:

XDocument xDocument = new XDocument(
new XDeclaration("1.0", "UTF-8", null),
new XElement("Request",
new XElement("Operation", "Testing"),
new XElement("Count","2"),
new XElement("Params", invoices.Select(x =>
new XElement("Invoice",
new XElement("Field",
new XAttribute("name","CustomerNo"),
new XAttribute("value","10000")),
new XElement("Field",
new XAttribute("name","Email"),
new XAttribute("value","testemail@yahoo.com")),
new XElement("Field",
new XAttribute("name","Invoice"),
new XAttribute("value",x)))))));

关于c# - 使用 XMLDocument C# xml 添加多个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52083613/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com