0
我正在嘗試讀取XML文件並查找字段的值。XElement.Decendents.First找不到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);
謝謝。如何在代碼中構建元素的示例中不需要這樣做。我想在向XElement中讀取一個字符串時會忽略文件中的名稱空間? – Yoav
您在代碼中構建的示例不會生成相同的XML。在第一行的輸出處仔細看*,你會發現它在'ReqHdr'和'ReqTxInf'元素中有'xmlns =「」',因爲除了'Document'元素之外,沒有其他元素存在於命名空間中。 –