我有一个XML文件,我想从中读取所有XmlTextReader
行。这是xml文件的示例:
<?xml version="1.0" encoding="utf-8"?>
<CodeSigns>
<CodeSign Format="1.0.0">
<Header>
<Title>AAA</Title>
<Shortcut>AAA</Shortcut>
<Description>AAA</Description>
<Author>Viva</Author>
<LoadTypes>
<LoadType>Expansion</LoadType>
</LoadTypes>
</Header>
<Sign>
<Declarations />
<Code Language="SQL Server" Kind="SQL Server"><![CDATA[SELECT TOP 100 [Id]
,[TotalSeconds]
,CAST('<![CDATA[' + [Parameters] + ']]]]><![CDATA[>' AS XML) as [Parameters]
,CAST('<![CDATA[' + [Query] + ']]]]><![CDATA[>' AS XML) as [Query]
,CAST('<![CDATA[' + [StackTrace] + ']]]]><![CDATA[>' AS XML) as [StackTrace]
,[CreateDate]
,[MachineName]
,[UserName]
,CAST('<![CDATA[' + [Exception] + ']]]]><![CDATA[>' AS XML) as [Exception]
,CAST('<![CDATA[' + [InnerException] + ']]]]><![CDATA[>' AS XML) as [InnerException]
,[CommandType]
FROM [QMaster].[dbo].[LogSlowQueries]
where CreateDate > CONVERT(DATE,GETDATE())
order by totalseconds desc]]>
</Code>
</Sign>
</CodeSign>
</CodeSigns>
某些元素对我们来说并不重要,并且从Code
元素读取时会发生问题,因为只读取了三行而不是全部。
用于读取此文件的C#代码如下:
public void Load(string path) {
filename = Path.GetFileName(path);
try {
using (XmlTextReader reader = new XmlTextReader(path)) {
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element) {
switch (reader.Name) {
case "Title":
title = ReadProperty(reader);
break;
case "ToolTip":
tooltip = ReadProperty(reader);
break;
case "Description":
description = ReadProperty(reader);
break;
case "Author":
author = ReadProperty(reader);
break;
case "Code":
language = reader.GetAttribute("Language");
code = ReadProperty(reader);
break;
}
}
}
}
}
catch (XmlException) {
}
}
private string ReadProperty(XmlReader reader) {
if (reader.IsEmptyElement)
return string.Empty;
reader.Read();
return reader.Value;
}
我们需要从XmlNodeType.Element
中获取名称为Code
的所有行,但是reader.Value
仅返回图片中的三行:
请帮助
答案 0 :(得分:1)
我通常发现使用Linq2Xml更容易。借助XPath:
var xDoc = XDocument.Load(FILENAME);
var title = (string)xDoc.XPathSelectElement("/CodeSigns/CodeSign/Header/Title");
var author = (string)xDoc.XPathSelectElement("/CodeSigns/CodeSign/Header/Author");
var code = (string)xDoc.XPathSelectElement("/CodeSigns/CodeSign/Sign/Code");
OR
var xDoc = XDocument.Load(FILENAME);
var topElem = xDoc.XPathSelectElement("/CodeSigns/CodeSign");
var title = (string)topElem.XPathSelectElement("Header/Title");
var author = (string)topElem.XPathSelectElement("Header/Author");
var code = (string)topElem.XPathSelectElement("Sign/Code");