我使用此代码创建了一个使用XMLWriter创建的简单XML文件:
using (XmlWriter writer = XmlWriter.Create("c:\\temp\\data.xml"))
{
writer.WriteStartElement("ScaleFactors");
writer.WriteStartAttribute("CorrectionFactorX");
writer.WriteValue(CorrectionFactorX);
writer.WriteEndAttribute();
writer.WriteStartAttribute("CorrectionFactorY");
writer.WriteValue(CorrectionFactorY);
writer.WriteEndAttribute();
writer.WriteStartAttribute("CorrectionFactorZ");
writer.WriteValue(CorrectionFactorZ);
writer.WriteEndAttribute();
writer.WriteEndElement();
writer.Flush();
}
XML文件看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<ScaleFactors CorrectionFactorX="1"
CorrectionFactorY="1"
CorrectionFactorZ="1" />
(CorrectionFactorX / Y / Z是双打)现在我想用XMLReader读回它们但是失败了。我试过MoveToAttribute / GetAttribute没有成功。任何提示和代码示例都表示赞赏。
谢谢!
答案 0 :(得分:1)
如果你可以使用XDoc,那么
void Main()
{
var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ScaleFactors CorrectionFactorX=\"1.31\" CorrectionFactorY=\"1\" CorrectionFactorZ=\"1\" />";
var xdoc = XDocument.Parse(xml);
var cfx = Double.Parse(xdoc.Element("ScaleFactors").Attribute("CorrectionFactorX").Value);
Console.WriteLine (cfx);
}
如果你坚持使用XmlReader,那么
void Main()
{
var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ScaleFactors CorrectionFactorX=\"1.31\" CorrectionFactorY=\"1\" CorrectionFactorZ=\"1\" />";
using (var reader = XmlReader.Create(new StringReader(xml)))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
Console.WriteLine(reader.Name);
var attc = reader.AttributeCount;
for (int i = 0; i < attc; i++)
{
Console.WriteLine(reader.GetAttribute(i));
}
}
}
}
}
(MSDN处理XML不同部分的好例子,但XDocument
更好“
答案 1 :(得分:0)
使用XmlDocument -
var xml = new XmlDocument();
xml.Load("xmlPath");
var match = xml.DocumentElement.Attributes;
foreach (XmlAttribute item in match)
{
Console.WriteLine(item.Value);
}