2013-03-06 5 views
1

В C# Я использую следующий код для чтения в XML-файле в XmlDocument. При этом я пытаюсь выбрать все узлы категории, независимо от их конкретного идентификатора категории, используя XPath. В общей сложности у меня более 200 категорий, поэтому их выбор по одному не является вариантом.Как выбрать узлы XML категории с XPath независимо от конкретных идентификаторов?

Я пробовал бесчисленные вариации «категории», «/ category», «// catalog/category» и т. Д. Однако nodeList всегда возвращает null. Я также пробовал следить за следующим сайтом вместе со многими другими. Любая помощь или руководство будут с благодарностью оценены.

w3 schools

XPath Examples - MSDN

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. 
+0

Namespaces. Обратите внимание, что while * в документе * вы можете сказать фронт 'xmlns =" ​​... "', чтобы означать, что все неприкрашенные имена находятся в этом пространстве имен **, вы не можете сделать это в xpath ** - в xpath, который концептуально стоит * отдельно * из любого документа, вы должны точно указать имена имен пространств имен, обычно используя 'XmlNamespaceManager'. – AakashM

ответ

1

Поскольку ваш XML использует явное пространство имен, то кажется, что вы должны указать его в методе SelectNodes:

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); 
nsmgr.AddNamespace("cc", "http://www.site.com/catalog/2012-10-31"); 
XmlNodeList nodelist = doc.SelectNodes("/cc:catalog/cc:category", nsmgr);