【发布时间】:2015-07-28 13:07:48
【问题描述】:
我有一些代码使用 XmlDocument 从具有命名空间的 xml 文件中读取。我的挑战是我现在正在读取硬编码的文件的命名空间,我将其传递给 XmlNamespaceManager。我想为我的方法更灵活一点。从任何类型的 xml 文件中读取。如果它有命名空间,则使用命名空间管理器来读取元素,而无需对命名空间进行硬编码。如果文件没有命名空间,则去前进,只需解析它。下面是我所做的。
xmldoc = new XmlDocument ();
xmldoc.Load (fileLocation);
XmlNamespaceManager nameSpaceManager = new XmlNamespaceManager(xmldoc.NameTable);
nameSpaceManager.AddNamespace ("ns","http://schemas.sample.data.org/2005");
XmlNodeList nodeList = xmldoc.SelectNodes("/ns:Demo/ns:Items", nameSpaceManager);
if (nodeList != null)
{
foreach (XmlNode childNode in nodeList)
{
string first = childNode.SelectSingleNode ("ns:First", nameSpaceManager).InnerText;
string second= childNode.SelectSingleNode ("ns:Second", nameSpaceManager).InnerText;
string third = childNode.SelectSingleNode ("ns:Third", nameSpaceManager).InnerText;
}
}
这是我正在使用的示例 xml 文件
<Demo xmlns:i="http://www.justasample.com" xmlns="http://schemas.sample.data.org/2005">
<Items>
<First>first</First>
<Second>second</Second>
<Third>third</Third>
</Items>
</Demo>
【问题讨论】:
-
有什么理由不使用 XDocument?这使得一切,尤其是。命名空间,容易得多。
-
好的,它不是真正的重复。但是,请更清楚地了解您当前的方法适用或无效。
-
@HenkHolterman ,它不一定只是 XmlDocument。我愿意接受任何其他建议。我想我把它放在问题中,因为这是我已经实施的。并澄清我的问题,我目前的方法效果不佳,因为名称空间是硬编码的。我需要摆脱它并使其能够与任何 xml 文件一起使用。
标签: c# xml namespaces