我有一个看起来像这样的示例 xml 文件。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<TextBlock Text="First Text" Margin="5"/>
<Label Content="Second Text" HorizontalAlignment="Center"/>
<TextBox Text="Third Text"/>
<GroupBox Header="Fourth Text">
Fifth Text
that extends to another line.
</GroupBox>
<Button Content="Sixth Text"/>
<Frame Content="<Seventh Text>"></Frame>
<ComboBox>
Eighth Text</ComboBox>
<Label Content="{Binding LabelText}" HorizontalAlignment="Center"/>
</StackPanel>
</Grid>
我的输出文件如下所示:
(4)Title="MainWindow"
(7)Text="First Text"
(8)Content="Second Text"
(9)Text="Third Text"
(10)Header="Fourth Text"
(11) Fifth Text that extends to another line.
(14)Content="Sixth Text"
(15)Content="<Seventh Text>"
(17) Eighth Text
这主要是我想要的。但是,由于某种原因,我只得到“标题”、“文本”和“内容”等等。但我希望它打印出“TextBlock Text”和“Label Content”以及“TextBox Text”和“Button Content”等等。我正在使用 XmlTextReader,但似乎找不到任何支持将其打印出来。reader.Name 只是打印出我已经拥有的内容。
这是我的代码:
public void ParseXml(String filename)
{
XmlTextReader reader = new XmlTextReader(filename);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
if (reader.LineNumber < 4)
{
continue;
}
//WriteLine(Path.GetFullPath(filename));
if(reader.Name != "Width" && reader.Name != "Height" && reader.Name != "Margin"
&& reader.Name != "HorizontalAlignment")
WriteLine("(" + reader.LineNumber + ")" + reader.ReadOuterXml());
}
break;
case XmlNodeType.Text:
WriteLine("(" + (reader.LineNumber + 1) + ") " + reader.Value.Replace("\r\n","").Trim());
break;
case XmlNodeType.EndElement:
break;
}
}
reader.Close();
}
谢谢!