傳回 XmlNodeList,其中包含符合指定之 Name 的所有子代項目清單

  • 5272
  • 0
  • C#
  • 2013-09-25

傳回 XmlNodeList,其中包含符合指定之 Name 的所有子代項目清單

由TagName取Elements
XmlDocument.GetElementsByTagName 方法 (String)
 
<?xml version='1.0'?>
<!-- This file represents a fragment of a book store inventory database -->
<bookstore>
  <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0">
    <title>The Autobiography of Benjamin Franklin</title>
    <author>
      <first-name>Benjamin</first-name>
      <last-name>Franklin</last-name>
    </author>
    <price>8.99</price>
  </book>
  <book genre="novel" publicationdate="1967" ISBN="0-201-63361-2">
    <title>The Confidence Man</title>
    <author>
      <first-name>Herman</first-name>
      <last-name>Melville</last-name>
    </author>
    <price>11.99</price>
  </book>
  <book genre="philosophy" publicationdate="1991" ISBN="1-861001-57-6">
    <title>The Gorgias</title>
    <author>
      <name>Plato</name>
    </author>
    <price>9.99</price>
  </book>
</bookstore>

private string GetFirstElementsByTagName(string strXml, string TagName)
{
     #region "傳回 符合指定之 Name 的第一個子代項目字串"
     XmlDocument doc = new XmlDocument();
     doc.LoadXml(strXml);
     XmlNodeList elemList = doc.GetElementsByTagName(TagName);
     string strRtn = elemList.Count > 0 ? elemList[0].InnerXml : "";

     return strRtn;
     #endregion
}

private List MyGetElementsByTagName(string strXml, string TagName)
{
     #region "傳回 XmlNodeList,其中包含符合指定之 Name 的所有子代項目清單"
     List sList = new List(); ;

     XmlDocument doc = new XmlDocument();
     doc.LoadXml(strXml);
     XmlNodeList elemList = doc.GetElementsByTagName(TagName);
     for (int i = 0; i < elemList.Count; i++)
     {
         sList.Add(elemList[i].InnerXml);
     }
     return sList;
     #endregion
}