如下XML文件:
<?xml version="1.0" encoding="utf-8"?>
<INTELLISENSE>
  <Groups>
    <Group Name="CLASS">
      <Variables>
        <Variable Name="ON_ALARM" Desc="" Type="Boolean" />
        <Variable Name="ALARM_RESET_COMMAND" Desc="" Type="Boolean" />
        <Variable Name="C11" Desc="" Type="Boolean" />
        <Variable Name="C12" Desc="" Type="Boolean" />
        <Variable Name="C13" Desc="" Type="Boolean" />
        <Variable Name="C14" Desc="" Type="Boolean" />
        <Variable Name="C15" Desc="" Type="Boolean" />
        <Variable Name="C16" Desc="" Type="Boolean" />
        <Variable Name="C21" Desc="" Type="Boolean" />
        <Variable Name="C22" Desc="" Type="Boolean" />
        <Variable Name="C23" Desc="" Type="Boolean" />
        <Variable Name="C24" Desc="" Type="Boolean" />
        <Variable Name="C25" Desc="" Type="Boolean" />
        <Variable Name="C26" Desc="" Type="Boolean" />
        <Variable Name="C31" Desc="" Type="Boolean" />
        <Variable Name="C32" Desc="" Type="Boolean" />
        <Variable Name="C33" Desc="" Type="Boolean" />
      </Variables>
    </Group>
    <Group Name="EVENT">
      <Variables>
        <Variable Name="CurrentDevice" Type="String" />
        <Variable Name="VR4CommError" Type="Boolean" />
      </Variables>
    </Group>
    <Group Name="FUNCTION">
      <Variables>
        <Variable Name="IDLE_TIME_SECOND" Desc="" Type="UInt16" />
        <Variable Name="IDLE_TIME_HOUR/MINUTE" Desc="" Type="UInt16" />
        <Variable Name="UTILISED_TIME_SECOND" Desc="" Type="UInt16" />
        <Variable Name="UTILISED_TIME_HOUR/MINUTE" Type="UInt16" />
        <Variable Name="OCCUPITE_TIME_SECOND" Desc="" Type="UInt16" />
        <Variable Name="OCCUPITE_TIME_HOUR/MINUTE" Desc="" Type="UInt16" />
        <Variable Name="TOTAL_TIME_FOR_EMERGENCY" Desc="" Type="UInt32" />
      </Variables>
    </Group>
    <Group Name="INTERFACE">
      <Variables>
        <Variable Name="IDLE_TIME_SECOND" Desc="" Type="UInt16" />
        <Variable Name="IDLE_TIME_HOUR/MINUTE" Desc="" Type="UInt16" />
        <Variable Name="UTILISED_TIME_SECOND" Desc="" Type="UInt16" />
        <Variable Name="UTILISED_TIME_HOUR/MINUTE" Type="UInt16" />
        <Variable Name="OCCUPITE_TIME_SECOND" Desc="" Type="UInt16" />
        <Variable Name="OCCUPITE_TIME_HOUR/MINUTE" Desc="" Type="UInt16" />
        <Variable Name="TOTAL_TIME_FOR_EMERGENCY" Desc="" Type="UInt32" />
      </Variables>
    </Group>
    <Group Name="PROPERTY">
      <Variables>
        <Variable Name="IDLE_TIME_SECOND" Desc="" Type="UInt16" />
        <Variable Name="IDLE_TIME_HOUR/MINUTE" Desc="" Type="UInt16" />
        <Variable Name="UTILISED_TIME_SECOND" Desc="" Type="UInt16" />
        <Variable Name="UTILISED_TIME_HOUR/MINUTE" Type="UInt16" />
        <Variable Name="OCCUPITE_TIME_SECOND" Desc="" Type="UInt16" />
        <Variable Name="OCCUPITE_TIME_HOUR/MINUTE" Desc="" Type="UInt16" />
        <Variable Name="TOTAL_TIME_FOR_EMERGENCY" Desc="" Type="UInt32" />
      </Variables>
    </Group>
  </Groups>
</INTELLISENSE>
想从XML中把各个"Name"的值读取出来,并且按Group Name类别,保存成一个Collection,如何才能实现阿?跪求代码

解决方案 »

  1.   

    http://www.cnblogs.com/kiddo/archive/2007/09/03/879932.html 
      

  2.   

                DataSet ds = new DataSet();
                ds.ReadXml(Server.MapPath("~/xmlFile.xml"));
                DataTable dtGroup = ds.Tables["Group"];
                DataTable dtVariable = ds.Tables["Variable"];
      

  3.   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml.Linq;namespace SimpleTester2.test1 {
        class Class1 : ITest {
            #region ITest 成员
            Dictionary<string , string> datastore = new Dictionary<string , string>(); int  = 0;
            /// <summary>
            /// 想从XML中把各个"Name"的值读取出来,并且按Group Name类别,保存成一个Collection,如何才能实现阿?跪求代码
            /// </summary>
            public void Run() {
                XDocument xd = XDocument.Load("test1/test.xml");
                foreach (XElement item in xd.Descendants()) {
                    if (item.Parent != null && item.Parent.Parent != null &&item.Parent.Parent.Attribute("Name")!=null&& item.Parent.Parent.Attribute("Name").Value == "CLASS") {
                        datastore.Add("CLASS"+.ToString() , item.Attribute("Name").Value);
                        ++;
                    } else if (item.Parent != null && item.Parent.Parent != null && item.Parent.Parent.Attribute("Name") != null && item.Parent.Parent.Attribute("Name").Value == "EVENT") {
                        datastore.Add("EVENT" + .ToString() , item.Attribute("Name").Value);
                        ++;
                    } else if (item.Parent != null && item.Parent.Parent != null && item.Parent.Parent.Attribute("Name") != null && item.Parent.Parent.Attribute("Name").Value == "FUNCTION") {
                        datastore.Add("FUNCTION" + .ToString() , item.Attribute("Name").Value);
                        ++;
                    } else if (item.Parent != null && item.Parent.Parent != null && item.Parent.Parent.Attribute("Name") != null && item.Parent.Parent.Attribute("Name").Value == "FUNCTION") {
                        datastore.Add("INTERFACE" + .ToString() , item.Attribute("Name").Value);
                        ++;
                    } else if (item.Parent != null && item.Parent.Parent != null && item.Parent.Parent.Attribute("Name") != null && item.Parent.Parent.Attribute("Name").Value == "PROPERTY") {
                        datastore.Add("PROPERTY" + .ToString() , item.Attribute("Name").Value);
                        ++;
                    }
                }
                Console.Read();
            }        #endregion
        }
      

  4.   

    代码有点复杂 ,几处你改一下,我测试过,可以满足你提出的这些要求,结果放到一个字典里取的时候你可以这样foreach(var item in this.dic){
      if(item.Key.SubString(0,item.Key.Length-1)=="CLASS")
      {
          //...
      }
      //...
    }
      

  5.   

    另外可以使用XmlDocument配合 XPath表达式来做
      

  6.   

    struct XGroupType
            {            public XGroupType(string _GroupName, string _Name)
                {
                    GroupName = _GroupName;
                    Name = _Name;            }
                string GroupName;
                string Name;            public override string ToString()
                {
                    return "GroupName: " + GroupName + " - Name: " + Name;
                }        }
            void readXML()
            {            XmlDocument doc = new XmlDocument();
                doc.Load("c:\\1.xml");
                XmlNodeList list = doc.SelectNodes("/INTELLISENSE/Groups/Group");
                string groupName = "";
                string sName = "";
                XGroupType myType;
                List<XGroupType> myList = new List<XGroupType>();
                foreach (XmlNode node in list)
                {                groupName = node.Attributes["Name"].Value;                foreach (XmlNode oNode in node.SelectNodes("Variables/Variable"))
                    {                    sName = oNode.Attributes["Name"].Value;
                        myType = new XGroupType(groupName, sName);
                        myList.Add(myType);                }            }
                //test
                MessageBox.Show(myList.Count.ToString());
                MessageBox.Show(myList[0].ToString());
                MessageBox.Show(myList[1].ToString());
            }
    调用:readXML();
      

  7.   

    看到一篇很好的练习xercesc的例子,和大家分享
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE person SYSTEM "a.dtd"><person>
    <people>
    <name>陈</name>
    <sex>male</sex>
    <age>30</age>
    </people>
    <people>
    <name>abched</name>
    <sex>female</sex>
    <age>1</age>
    </people>
    </person>声明了一个XML处理类:struct suPerson
    {
    string _name;
    string _sex;
    int _age;
    };class TParse
    {
    private:
    string _strErrMsg;DOMImplementation *_impl;
    DOMBuilder *_parser;
    DOMWriter* _writer;
    DOMDocument* _doc;
    DOMDocument* _newDoc;vector<suPerson> _vecPerson;bool parseNode(DOMNode *n);
    public:
    TParse();
    ~TParse();bool parse(const char* strXmlFile);
    bool newDoc(const char* strXmlFile);string getErrMsg()
    {
    return _strErrMsg;
    }
    vector<suPerson> getVector()
    {
    return _vecPerson;
    }
    };类的具体定义如下:#include "Parse.h"TParse::TParse()
    {
    try 
    {
    XMLPlatformUtils::Initialize();
    }
    catch (const XMLException& toCatch) 
    {
    char* message = XMLString::transcode(toCatch.getMessage());
    _strErrMsg = message;
    XMLString::release(&message);
    throw _strErrMsg;
    }
    XMLCh tempStr[100];
    XMLString::transcode("LS", tempStr, 99);
    _impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
    _parser = _impl->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS, 0);_writer = ((DOMImplementationLS*)_impl)->createDOMWriter();// optionally, set some DOMWriter features
    // set the format-pretty-print feature
    if (_writer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true))
    _writer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, true);// set the byte-order- feature
    if (_writer->canSetFeature(XMLUni::fgDOMWRTBOM, true))
    _writer->setFeature(XMLUni::fgDOMWRTBOM, true);
    }TParse::~TParse()
    {
    _parser->release();
    if (_newDoc)
    _newDoc->release();
    _writer->release();
    }bool TParse::parse(const char* strXmlFile)
    {
    try 
    {
    _doc = _parser->parseURI(XMLString::transcode(strXmlFile));
    }
    catch (const XMLException& toCatch) 
    {
    char* message = XMLString::transcode(toCatch.getMessage());
    _strErrMsg = message;
    XMLString::release(&message);
    throw _strErrMsg;
    }
    catch (const DOMException& toCatch) 
    {
    char* message = XMLString::transcode(toCatch.msg);
    _strErrMsg = message;
    XMLString::release(&message);
    throw _strErrMsg;
    }
    catch (...) 
    {
    _strErrMsg = "Unexpected Exception n";
    throw _strErrMsg;
    }if (!_doc)
    {
    _strErrMsg = "_doc is null";
    return false;
    }
    DOMNode* n = (DOMNode*)_doc->getDocumentElement();
    _vecPerson.clear();if (!n)
    {
    _strErrMsg = "it is not an legal node";
    return false;
    }if (n) 
    {
    if (n->getNodeType() == DOMNode::ELEMENT_NODE)
    {
    DOMNodeList* nodeList = n->getChildNodes();
    unsigned int nListLen = nodeList->getLength();
    for (unsigned int i=0; i<nListLen; ++i)
    {
    DOMNode* nodeTemp = nodeList->item(i);
    if (nodeTemp->getNodeType() == DOMNode::ELEMENT_NODE)
    {
    suPerson suTemp;
    memset(&suTemp, 0, sizeof(suTemp));
    for (DOMNode* node1=nodeTemp->getFirstChild(); node1!=0; node1=node1->getNextSibling())
    {char* name = XMLString::transcode(node1->getNodeName());
    string strTemp = name;
    if (strTemp == "name")
    {
    suTemp._name = XMLString::transcode(node1->getFirstChild()->getNodeValue());
    node1->getFirstChild()->setNodeValue(XMLString::transcode((suTemp._name+" hello").c_str()));
    }
    else if (strTemp == "sex")
    {
    suTemp._sex = XMLString::transcode(node1->getFirstChild()->getNodeValue());
    }
    else if (strTemp == "age")
    {
    suTemp._age = XMLString::parseInt(node1->getFirstChild()->getNodeValue());
    }XMLString::release(&name);
    }
    _vecPerson.push_back(suTemp);
    }
    }}
    }
    return true;
    }//---------------------------------------------------------------------------
    bool TParse::newDoc(const char* strXmlFile)
    {
    try 
    {
    _newDoc = _impl->createDocument();
    }
    catch (const XMLException& toCatch) 
    {
    char* message = XMLString::transcode(toCatch.getMessage());
    _strErrMsg = message;
    XMLString::release(&message);
    throw _strErrMsg;
    }
    catch (const DOMException& toCatch) 
    {
    char* message = XMLString::transcode(toCatch.msg);
    _strErrMsg = message;
    XMLString::release(&message);
    throw _strErrMsg;
    }
    catch (...) 
    {
    _strErrMsg = "Unexpected Exception n";
    throw _strErrMsg;
    }DOMElement* root = _newDoc->createElement(XMLString::transcode("person"));
    for (unsigned int i=0; i<2; ++i)
    {
    DOMElement* item = _newDoc->createElement(XMLString::transcode("people"));
    DOMElement* name = _newDoc->createElement(XMLString::transcode("name"));
    DOMAttr* attr = _newDoc->createAttribute(XMLString::transcode("id"));
    attr->setNodeValue(XMLString::transcode("hello"));
    name->appendChild(_newDoc->createTextNode(XMLString::transcode("C陈")));
    name->setAttributeNode(attr);
    DOMElement* sex = _newDoc->createElement(XMLString::transcode("male"));
    sex->appendChild(_newDoc->createTextNode(XMLString::transcode("male")));
    DOMElement* age = _newDoc->createElement(XMLString::transcode("age"));
    age->appendChild(_newDoc->createTextNode(XMLString::transcode("30")));
    item->appendChild(name);
    item->appendChild(sex);
    item->appendChild(age);
    root->appendChild(item);
    }
    _newDoc->appendChild(root);// construct the LocalFileFormatTarget
    XMLFormatTarget *myFormatTarget = new LocalFileFormatTarget(strXmlFile);// serialize a DOMNode to the local file "myXMLFile.xml"
    _writer->writeNode(myFormatTarget, *_newDoc->getDocumentElement());// optionally, you can flush the buffer to ensure all contents are written
    myFormatTarget->flush();// release the memory
    delete myFormatTarget;
    return true;
    }测试代码:#include "Parse.h"int main (int argc, char* args[]) 
    {
    try
    {
    TParse parse;
    if (!parse.parse("a.xml"))
    {
    cout << "error: " << parse.getErrMsg() << endl;
    }
    vector<suPerson> vecTemp = parse.getVector();
    for (unsigned int i=0; i<vecTemp.size(); ++i)
    {
    cout << i << "--------------" << endl;
    cout << "name: " << vecTemp[i]._name << endl;
    cout << "sex: " << vecTemp[i]._sex << endl;
    cout << "age: " << vecTemp[i]._age << endl;
    }
    cout << "--------------------------------" << endl;
    parse.newDoc("b.xml");
    }
    catch(const string& str)
    {
    cout << "error: " << str << endl;
    }
    cin.get();
    return 0;
    }