c# xml multiple elements
本文关键字:elements multiple xml | 更新日期: 2023-09-27 18:01:23
这是我在检索这些多个元素的两次尝试,第一次只选择第一个框&第一个文本元素
第二个检索所有,但它们不是单独的变量——
var xmlDoc = document.Root.Elements("Page")
.Select(element => new
{
Box = (string)element.Element("Box"),
Text = (string)element.Element("Text"),
}).ToList();
var xmlDoc = document.Root.Descendants("Page")
.Elements()
.Select(x => x.Value)
.ToList();
xml示例:
<?xml version="1.0" standalone="yes"?>
<PrintJob>
<Page>
<Box>0000,0000,0190,0135</Box>
<Box>0050,0100,0190,0135</Box>
<Text>0000,0000,"ABCdef123456"</Text>
<Text>0000,0000,"ABCdef123456"</Text>
<Text>0000,0050,"ABCdef123456"</Text>
<Text>0000,0050,"ABCdef123456"</Text>
</Page>
</PrintJob>
循环检索元素:
foreach (var x in xmlDoc)
{
//result += "box: " + x.Box + "'n";
//result += "text: " + x.Text + "'n";
result += "x: " + x + "'n";
}
如何得到这样的结果:
box: 0000,0000,0190,0135
box: 0050,0100,0190,0135
text: 0000,0000,"ABCdef123456"
text: 0000,0000,"ABCdef123456"
text: 0000,0050,"ABCdef123456"
text: 0000,0050,"ABCdef123456"
你在找这样的东西吗?
var page = document.Element("PrintJob")
.Element("Page");
var boxes = page.Elements("Box")
.Select(x => (string)x)
.ToList();
var texts = page.Elements("Text")
.Select(x => (string)x)
.ToList();
foreach (var box in boxes)
Console.WriteLine("Box: " + box);
foreach (var text in texts)
Console.WriteLine("Text: " + text);
输出:<>之前箱:0000、0000、0190、0135箱:0050、0100、0190、0135文字:0000,0000,"ABCdef123456"文字:0000,0000,"ABCdef123456"文字:0000,0050,"ABCdef123456"文字:0000,0050,"ABCdef123456"之前
var items = document.Element("PrintJob")
.Element("Page")
.Elements()
.Select(x => x.Name.LocalName + ": " + (string)x)
.ToList();
foreach (var item in items)
Console.WriteLine(item);
输出:<>之前箱:0000、0000、0190、0135箱:0050、0100、0190、0135文字:0000,0000,"ABCdef123456"文字:0000,0000,"ABCdef123456"文字:0000,0050,"ABCdef123456"文字:0000,0050,"ABCdef123456"之前
var items = document.Element("PrintJob")
.Element("Page")
.Elements()
.Select(x => new
{
Box = (x.Name.LocalName == "Box")
? (string)x
: null,
Text = (x.Name.LocalName == "Text")
? (string)x
: null
})
.ToList();
foreach (var item in items)
Console.WriteLine("Box: " + item.Box + " Text: " + item.Text);
输出:<>之前框:0000,0000,0190,0135文本:方框:0050、0100、0190、0135框:文本:0000,0000,"ABCdef123456"框:文本:0000,0000,"ABCdef123456"框:文本:0000,0050,"ABCdef123456"框:文本:0000,0050,"ABCdef123456"
var xmlDoc = document.Root.Descendants("Page")
.Elements();
foreach(var x in xmlDoc)
{
Console.WriteLine(x.Name + ": " + x.Value);
}