【发布时间】:2016-11-24 15:42:02
【问题描述】:
我正在尝试读取 XML 文件并查找字段的值。
我正在读取文件“MyMessage.txt”:
<?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:com.company:request.001">
<ReqHdr>
<AppInstanceId>AAAA</AppInstanceId>
</ReqHdr>
<ReqTxInf>
<PmtId>
<TxId>123456</TxId>
</PmtId>
<MsgTyp>REQUEST</MsgTyp>
</ReqTxInf>
</Document>
代码如下:
// Read XElement from file
element = XElement.Parse(System.IO.File.ReadAllText(
System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"MyMessage.txt")));
try
{
Console.WriteLine(element);
Console.WriteLine("TxId is:" + element.Descendants("TxId").First().Value);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
文件被正确读取并写入控制台,但搜索 TxId 失败。
这次我尝试在代码中重复这个创建文件,并且相同的代码找到了 TxId:
// Create XEleemnt in code
XNamespace ns = "urn:com.company:request.001";
XElement element = new XElement(ns + "Document",
new XElement("ReqHdr",
new XElement("AppInstanceId", "AAAA")),
new XElement("ReqTxInf",
new XElement("PmtId",
new XElement("TxId", "123456")),
new XElement("MsgTyp", "request")));
try
{
Console.WriteLine(element);
Console.WriteLine();
Console.WriteLine("TxId is:" + element.Descendants("TxId").First().Value);
Console.WriteLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
分辨率
读取字段的行更改为包含名称空间
Console.WriteLine("TxId is:" + element.Descendants(element.Name.Namespace + "TxId").First().Value);
【问题讨论】: