1

私は次のようなXMLを持っています:

<RES>
 <MUL>
  <SIN>
   <KEY name="a">
    <VALUE>a1</VALUE>
   </KEY>
   <KEY name="b">
    <VALUE>b1</VALUE>
   </KEY>
   <KEY name="c">
    <VALUE>c1</VALUE>
   </KEY>
   <KEY name="need">
    <MUL>
     <SIN>
      <KEY name="needID">
       <VALUE>ID</VALUE>
      </KEY>
      <KEY name="needOther">
       <VALUE>other</VALUE>
      </KEY>
      <KEY name="needOther2">
       <VALUE>other2</VALUE>
      </KEY>
     </SIN>
    </MUL>
   </KEY>
  </SIN>
 </MUL>
</RES>

needID私の質問は、名前が?のノードから値 'id' を取得する方法です。

で試しました

XmlDocument xx = new XmlDocument();
xx.Load(MYDOC);

XmlNodeList node = xx.SelectNodes("/RES/MUL/SIN/KEY[@name='need']");

しかし、その後、needIDを選択できません

XDocument doc = new XDocument(node);
var cource = from x in doc.Descendants("KEY")
select new { ID = doc.Element("VALUE").Value };

私を助けてください!

ありがとう!:)

4

3 に答える 3

2

以下のようなものはいかがですか

XDocument doc = XDocument.Load("url");

var cource = from x in doc.Descendants("KEY")
                 where x.Attribute("name").Value == "needID" 
                 select new { ID = x.Element("VALUE").Value };

ありがとう

ディープ

于 2012-04-12T11:46:24.663 に答える
1

次のようなものが必要です。

// you're expecting only a single node - right?? So use .SelectSingleNode!
XmlNode node = xx.SelectSingleNode("/RES/MUL/SIN/KEY[@name='need']");

// if we found the node...
if(node != null)
{
    // get "subnode" inside that node
    XmlNode valueNode = node.SelectSingleNode("MUL/SIN/KEY[@name='needID']/VALUE");

    // if we found the <MUL>/<SIN>/<KEY name='needID'>/<VALUE> subnode....
    if(valueNode != null)
    {
        // get the inner text = the text of the XML element...
        string value = valueNode.InnerText;
    }
}

または、XML ドキュメント内に一致するノードが 1 つしかないことがわかっている場合は、それを 1 つの XPath 操作に結合することもできます。

// define XPath
string xpath = "/RES/MUL/SIN/KEY[@name='need']/MUL/SIN/KEY[@name='needID']/VALUE";

// you're expecting only a single node - right?? So use .SelectSingleNode!
XmlNode node = xx.SelectSingleNode(xpath);

// if we found the node...
if(node != null)
{
    // get the inner text = the text of the XML element...
    string value = node.InnerText;
}
于 2012-04-12T11:52:45.940 に答える
0
XmlDocument xml = new XmlDocument();

xml.Load(File.OpenRead(@"Your XML File"));

//XmlNodeList xnList = xml.SelectNodes("/RES/MUL/SIN/KEY");

//You can use something like the below if the XML file is large and you need to read in more than one
//foreach (XmlNode xn in xnList)
//{
//Have a seperate class to store the values
//class class = new class();
//class.ID = xn.SelectSingleNode("./@needID").Value;
//
//}
于 2012-04-12T11:57:36.863 に答える