在C#中使用带有xelement类的循环我希望得到以下结果!
<data>
<description>Cities that I have recently visited.</description>
<cities>
<city id="1">
<name>Chicago1</name>
<state>IN1</state>
</city>
<city id="2">
<name>Chicago2</name>
<state>IN2</state>
</city>
<city id="3">
<name>Chicago3</name>
<state>IN3</state>
</city>
</cities>
</data>
这是我到目前为止尝试过的代码!任何帮助?我需要使用循环并获得上述值。我使用的循环被评论..
namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
XElement xmlDataStore = new XElement("data",
new XElement("cities",
new XElement("city", new XAttribute("id", "1")),
new XElement("city", "Colombo"),
new XElement("name", "lname"),
new XElement("state", "0772569984")
)
)
;
//var list = from x in XElement.ReadFrom(xmlDataStore).Element("Node").Elements()
//select new
//{
// Name = x.Name,
// Value = (string)x
//};
Console.WriteLine(xmlDataStore);
Console.ReadLine();
}
}
}
我得到了什么...
<cities>
<city id="1">
<name>Chicago1</name>
<state>IN1</state>
</city>
</cities>
我想要的......
<data>
<description>Cities that I have recently visited.</description>
<cities>
<city id="1">
<name>Chicago1</name>
<state>IN1</state>
</city>
<city id="2">
<name>Chicago2</name>
<state>IN2</state>
</city>
<city id="3">
<name>Chicago3</name>
<state>IN3</state>
</city>
</cities>
</data>
答案 0 :(得分:0)
后裔检查
XDocument xdoc = XDocument.Load("Xml File Path"); //save that xml in "C:\test.xml "
IEnumerable<XElement> xEle = xdoc.XPathSelectElements("//cities");
if(xEle !=null)
{
foreach(XElement xE in Xelement.Descendants())
{
// here you will get everything ......
}
}
你可以循环
答案 1 :(得分:0)
好的,我仍然不知道真正的问题是什么,所以让我们从这开始:
private static void citiesXml()
{
const string desc = "Cities that I have recently visited.";
// set up a list of all the different cities
var list = new List<Tuple<string, string>>();
list.Add(new Tuple<string, string>("Chicago1", "IN1"));
list.Add(new Tuple<string, string>("Chicago2", "IN2"));
list.Add(new Tuple<string, string>("Chicago3", "IN3"));
var xmlDataStore = new XElement("data", new XElement("description", desc));
var xmlCities = new XElement("cities");
// loop through the list of cities and create a XElement for each single one
for (var i = 0; i < list.Count; i++)
{
xmlCities.Add(new XElement("city",
new XAttribute("id", i + 1),
new XElement("name", list[i].Item1),
new XElement("state", list[i].Item2)));
}
// add the cities to the data store object
xmlDataStore.Add(xmlCities);
Console.WriteLine(xmlDataStore);
Console.ReadLine();
}
这将打印:
<data>
<description>Cities that I have recently visited.</description>
<cities>
<city id="1">
<name>Chicago1</name>
<state>IN1</state>
</city>
<city id="2">
<name>Chicago2</name>
<state>IN2</state>
</city>
<city id="3">
<name>Chicago3</name>
<state>IN3</state>
</city>
</cities>
</data>
据我所知,唯一的区别是城市之间没有空行。丢失的空行是问题吗?