我正在嘗試創建 XML 檔案。我想在回圈中創建節點
下面的代碼是我要創建的
XDocument doc = new XDocument( new XElement("Bill", new XElement("ITEM", new XElement("Mat", new XElement("ID","1"), new XElement("Code"), new XElement("Name") ),//Mat new XElement("Store", new XElement("ID","1"), new XElement("Code"), new XElement("Name") ) )//ITEM )//Bill ); doc.save("Test.xml");
輸出
<Bill>
<Version>1.0</Version>
<ITEM>
<Mat>
<ID>1<ID/>
<Code />
<Name />
</Mat>
<Store>
<ID>1<ID/>
<Code />
<Name />
</Store>
</ITEM>
</Bill>
我需要像下面的輸出
<Bill>
<Version>1.0</Version>
<ITEM>
<Mat>
<ID>1<ID/>
<Code />
<Name />
</Mat>
<Store>
<ID>1<ID/>
<Code />
<Name />
</Store>
</ITEM>
<ITEM>
<Mat>
<ID>2<ID/>
<Code />
<Name />
</Mat>
<Store>
<ID>2<ID/>
<Code />
<Name />
</Store>
</ITEM>
<ITEM>
<Mat>
<ID>3<ID/>
<Code />
<Name />
</Mat>
<Store>
<ID>3<ID/>
<Code />
<Name />
</Store>
</ITEM>
</Bill>
筆記
I will get the value from db and pass it to xml nodes of (ID,Code,Name). I want to iterate in loop..
uj5u.com熱心網友回復:
這是結果的影像

您正在使用 XDocument(不是 xmlDocument),它是 xml linq。嘗試以下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication11
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
string ident = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><BILL></BILL>";
XDocument doc = XDocument.Parse(ident);
XElement bill = doc.Root;
bill.Add(new XElement("version","1.0"));
for (int i = 1; i <= 3; i )
{
XElement item = new XElement("ITEM");
bill.Add(item);
item.Add(new XElement("Mat", new object[] {
new XElement("ID",i),
new XElement("Code"),
new XElement("Name")
}));
item.Add(new XElement("Store", new object[] {
new XElement("ID",i),
new XElement("Code"),
new XElement("Name")
}));
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/411179.html
標籤:
上一篇:VisualStudio-aspx頁面中的未知黑標,如斷點
下一篇:Blazor未處理的例外:無法為型別“BlazorStrap.BSCarousel”的屬性“BlazorStrapSrc”提供值
