从 XML 文件中读取节点时遇到问题
这是我正在尝试读取的 XML 文件的片段。
<?xml version="1.0" encoding="UTF-8" ?>
<FMPXMLRESULT xmlns="http://www.filemaker.com/fmpxmlresult">
<ERRORCODE>0</ERRORCODE>
<PRODUCT BUILD="06-11-2010" NAME="FileMaker" VERSION="Pro 11.0v2" />
<DATABASE DATEFORMAT="M/d/yyyy" LAYOUT="" NAME="Appointments.fp7" RECORDS="13" TIMEFORMAT="h:mm:ss a" />
<METADATA>
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="CalDateCalc1" TYPE="DATE" />
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="CalDateCalc2" TYPE="DATE" />
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="CalDateCalc3" TYPE="DATE" />
...
</METADATA>
...
</FMPXMLRESULT>
我的目标是从 xml 文件中获取 NAME
属性和 TYPE
属性。我尝试过同时使用 XElement 和 XPath,但两者都不起作用。
foreach (var file in System.IO.Directory.EnumerateFiles(path, "*.xml", System.IO.SearchOption.TopDirectoryOnly))
{
var fileInfo = new System.IO.FileInfo(file);
var name = fileInfo.Name.Split('.')[0];
XElement root = XElement.Load(file);
if (!db.Tables.Contains(name))
{
XElement MetaData = root.Element("METADATA"); //This returns null
foreach(var field in MetaData.Elements("FIELD"))
{
//...
}
}
//...
}
当我尝试选择 METADATA
组时,选择返回 null。我的代码犯了什么错误?
Here is a snippet of the XML file I am trying to read.
<?xml version="1.0" encoding="UTF-8" ?>
<FMPXMLRESULT xmlns="http://www.filemaker.com/fmpxmlresult">
<ERRORCODE>0</ERRORCODE>
<PRODUCT BUILD="06-11-2010" NAME="FileMaker" VERSION="Pro 11.0v2" />
<DATABASE DATEFORMAT="M/d/yyyy" LAYOUT="" NAME="Appointments.fp7" RECORDS="13" TIMEFORMAT="h:mm:ss a" />
<METADATA>
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="CalDateCalc1" TYPE="DATE" />
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="CalDateCalc2" TYPE="DATE" />
<FIELD EMPTYOK="YES" MAXREPEAT="1" NAME="CalDateCalc3" TYPE="DATE" />
...
</METADATA>
...
</FMPXMLRESULT>
My goal is to get the the NAME
attribute and the TYPE
attribute out of the xml file. I have tried to use both XElement and XPath but I have gotten neither to work.
foreach (var file in System.IO.Directory.EnumerateFiles(path, "*.xml", System.IO.SearchOption.TopDirectoryOnly))
{
var fileInfo = new System.IO.FileInfo(file);
var name = fileInfo.Name.Split('.')[0];
XElement root = XElement.Load(file);
if (!db.Tables.Contains(name))
{
XElement MetaData = root.Element("METADATA"); //This returns null
foreach(var field in MetaData.Elements("FIELD"))
{
//...
}
}
//...
}
When I try to select the METADATA
group the selection returns null. What mistake am I making with my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
元素驻留在 XML 命名空间 中。您必须将该命名空间指定为 Element() 方法:请参阅 XName类以获取更多详细信息。
Your
<METADATA>
element resides in an XML namespace. You have to specify that namespace to the Element() method:See the XName class for more details.