Reputation: 11
I have xml document:
<users>
<user_tuple>
<userid>U01</userid>
<code>
<name>Tom Jones</name>
</code>
<rating>B</rating>
</user_tuple>
<user_tuple>
<userid>U02</userid>
<code>
<name>Mary Doe</name>
</code>
<rating>A</rating>
</user_tuple>
<user_tuple>
<userid>U03</userid>
<code>
<name>Dee Linquent</name>
</code>
<rating>D</rating>
</user_tuple>
How do I select only those (and all child nodes/elements) where Element("userid").value=="U01" and Element("name").Value=="Tom Jones" etc ie I want results:
<user_tuple>
<userid>U01</userid>
<code>
<name>Tom Jones</name>
</code>
<rating>B</rating>
</user_tuple>
I'm using C#
public void searchInfo(string rootNode, string Element1Name, string Element2Name, string Element1Val, string Element2Val){
////// Select rootNode and all descend nodes
var res = root.Elements("rootNode")
.Where(
x =>
(string)x.Element(Element1Name) == Element1Val&&
(string)x.Element(Element2Name) == Element2Val)
).ToList();
///////////
foreach (var node in res){
Debug.Writeline("Name {0} Value {1}", node.Name, node.Value)
}
Example:
searchInfo("rootNode","userid","code", "U01", "Tom Jones")
res = <userid>U01</userid>
<code>
<name>Tom Jones</name>
</code>
<rating>B</rating>
and result:
userid U01
name Tom Jones
rating B
Is that possible?
Upvotes: 0
Views: 109
Reputation: 117540
try this
var doc = XDocument.Parse(s);
var res = doc.Elements("users").Elements("user_tuple")
.Where(
x =>
(string)x.Element("userid") == "U01" &&
(string)x.Element("code").Element("name") == "TomJones")
).ToList();
Or use XPath:
var res = doc.XPathSelectElements("
users/user_tuple[userid='U01' and code[name='TomJones']]
").ToList();
Upvotes: 1