在 C# 中,我使用以下代码将 XML 文件读入 XmlDocument。在这样做时,我试图选择所有“类别”节点,而不管它们使用 XPath 的特定类别 ID。我总共有 200 多个类别,因此逐个选择它们并不是一个真正的选择。
我已经尝试了无数的“类别”、“/类别”、“//目录/类别”等变体。但是 nodeList 总是返回 null。我也尝试过关注以下网站以及其他许多网站。任何帮助或指导将不胜感激。
var doc = new XmlDocument();
doc.Load(filename);
XmlNodeList nodeList;
XmlNode root = doc.DocumentElement;
nodeList = root.SelectNodes("/catalog/category")
// Sample XML Document
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="http://www.site.com/catalog/2012-10-31" catalog-id="sports">
<header>
<image-settings>
<internal-location base-path="/"/>
<view-types>
<view-type>large</view-type>
<view-type>small</view-type>
<view-type>swatch</view-type>
</view-types>
<alt-pattern>${productname}</alt-pattern>
<title-pattern>${productname}</title-pattern>
</image-settings>
</header>
<category category-id="root">
<display-name xml:lang="x-default">Store Catalog</display-name>
<description xml:lang="x-default">Holds categories for Store</description>
<online-flag>true</online-flag>
<template/>
<page-attributes>
<page-title xml:lang="x-default">Store Catalog</page-title>
<page-description xml:lang="x-default">Welcome to the Store</page-description>
</page-attributes>
<custom-attributes>
<custom-attribute attribute-id="enableCompare">false</custom-attribute>
<custom-attribute attribute-id="showInMenu">false</custom-attribute>
</custom-attributes>
<refinement-definitions>
<refinement-definition type="category" bucket-type="none">
<display-name xml:lang="x-default">Category</display-name>
<sort-mode>category-position</sort-mode>
<cutoff-threshold>5</cutoff-threshold>
</refinement-definition>
</refinement-definitions>
</category>
<category category-id="whats-new">
<display-name xml:lang="x-default">NEW</display-name>
<online-flag>true</online-flag>
<parent>root</parent>
<position>25.0</position>
<template>rendering/category/categoryproducthits</template>
<page-attributes>
<page-title xml:lang="x-default">What's New - New at Store</page-title>
<page-description xml:lang="x-default">Learn what's new at the store.</page-description>
</page-attributes>
<custom-attributes>
<custom-attribute attribute-id="contentOnly">false</custom-attribute>
<custom-attribute attribute-id="displaySubNav">false</custom-attribute>
<custom-attribute attribute-id="dropdownNavSlot1">dropdown-left7</custom-attribute>
<custom-attribute attribute-id="enableCompare">false</custom-attribute>
<custom-attribute attribute-id="enableslotat3">true</custom-attribute>
<custom-attribute attribute-id="enableslotat4">true</custom-attribute>
<custom-attribute attribute-id="enableslotat9">true</custom-attribute>
<custom-attribute attribute-id="showInMenu">true</custom-attribute>
<custom-attribute attribute-id="showShadeSelector">false</custom-attribute>
<custom-attribute attribute-id="showSubCollectionsAsTabs">false</custom-attribute>
</custom-attributes>
</category>
// cut for brevity - the above category nodes are the same format as the rest of the XML document.