这是我尝试检索这些多个元素的两次尝试,第一次只选择第一个框和&第一个文本元素
第二个检索所有,但它们不是单独的变量 -
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"
答案 0 :(得分:2)
你在找这样的东西吗?
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);
输出:
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 items = document.Element("PrintJob")
.Element("Page")
.Elements()
.Select(x => x.Name.LocalName + ": " + (string)x)
.ToList();
foreach (var item in items)
Console.WriteLine(item);
输出:
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 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);
输出:
Box: 0000,0000,0190,0135 Text: Box: 0050,0100,0190,0135 Text: Box: Text: 0000,0000,"ABCdef123456" Box: Text: 0000,0000,"ABCdef123456" Box: Text: 0000,0050,"ABCdef123456" Box: Text: 0000,0050,"ABCdef123456"
答案 1 :(得分:0)
var xmlDoc = document.Root.Descendants("Page")
.Elements();
foreach(var x in xmlDoc)
{
Console.WriteLine(x.Name + ": " + x.Value);
}