Hi there. I'm sor of beginner in c# and want to compare the value of the elements form a XML file with other values wich i declare for example. My XML file looks like this:
<alarma>
<conditii>
<conditie>
<semnal>Umiditate</semnal>
<operator_semnal>=</operator_semnal>
<valoare>90</valoare>
</conditie>
<operator>&</operator>
<conditie>
<semnal>Temperatura</semnal>
<operator_semnal><</operator_semnal>
<valoare>37</valoare>
</conditie>
</conditii>
</alarma>
I want to compare the values from the nodes with other value that i declare and show a message depending on the result. Can anyone help me?

Dani AI

Generated

you are reading only the first child because you index into ChildNodes[0]. Instead, iterate all <conditie> elements and compare numerically, not with string.CompareTo (lexical). LINQ to XML makes this clean and readable. ’s pointer to the XML APIs is spot on, but here is a safer loop that walks every condition. (learn.microsoft.com)

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Xml.Linq;

var doc = XDocument.Load("licenta2.xml");
var conditions = doc.Root.Element("conditii");
string join = (string)conditions.Element("operator"); // "&" or "|"
bool andMode = join == "&";

var sensors = new Dictionary<string,double> {
    ["Umiditate"] = 36,
    ["Temperatura"] = 38
};

bool overall = andMode ? true : false;

foreach (var c in conditions.Elements("conditie"))
{
    string name = (string)c.Element("semnal");
    string op   = (string)c.Element("operator_semnal");
    double target = double.Parse((string)c.Element("valoare"),
                                 CultureInfo.InvariantCulture);

    if (!sensors.TryGetValue(name, out double actual)) continue;

    bool ok;
    if (op == "=" || op == "==") ok = actual == target;
    else if (op == "<") ok = actual < target;
    else if (op == ">") ok = actual > target;
    else if (op == "<=") ok = actual <= target;
    else if (op == ">=") ok = actual >= target;
    else if (op == "!=") ok = actual != target;
    else ok = false;

    overall = andMode ? (overall && ok) : (overall || ok);
    System.Windows.Forms.MessageBox.Show($"{name}: {actual} {op} {target} => {(ok ? "match" : "no match")}");
}

System.Windows.Forms.MessageBox.Show(overall ? "All conditions met" : "Conditions not met");

Two important gotchas and others will agree on:

  • In your XML, escape operators: use <operator_semnal>&lt;</operator_semnal> and <operator>&amp;</operator>. XML requires escaping < and &. (w3.org)
  • Parse numbers with an explicit culture to avoid locale issues (e.g., commas vs dots): double.Parse(..., CultureInfo.InvariantCulture). (learn.microsoft.com)

Recommended Answers

All 7 Replies

Read this (many more on Google)

Use System.Data.DataSet class or System.Xml.XmlDocument class to load xml document and navigate its element.

commented: why dont you provide some code -1

thanks for the reply but i want to know how i can store the elements value in a string for example so i can work easily with the values. I am using the Windows-based application. thanks

I was suggested by Mr. serkan to post code. Here is a sample which helps undead25 to solve his/her problem.

Xml file - sample.xml

<?xml version="1.0" encoding="utf-8" ?>
<alarma>
  <conditii>
    <conditie>
      <semnal>Umiditate</semnal>
      <operator_semnal>=</operator_semnal>
      <valoare>90</valoare>
    </conditie>
    <operator>&amp;</operator>
    <conditie>
      <semnal>Temperatura</semnal>
      <operator_semnal></operator_semnal>
      <valoare>37</valoare>
    </conditie>
  </conditii>
</alarma>

Place this code in any event of your form.

System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(@"c:\testapp\WindowsFormsApplication2\sample.xml");

            // Root element
            System.Xml.XmlElement root = doc.DocumentElement;

            System.Xml.XmlElement conditie=(System.Xml.XmlElement)root.ChildNodes[0].ChildNodes[0];
            string semnal = conditie.ChildNodes[0].InnerText;
            string operator_semnal = conditie.ChildNodes[1].InnerText;
            string valoare = conditie.ChildNodes[2].InnerText;
            string op = root.ChildNodes[0].ChildNodes[1].InnerText; ;

            MessageBox.Show(semnal  + " " + operator_semnal  + " " + valoare );
            MessageBox.Show(op);

Thank you very much for the answer so far and i'm sory fot this late posting. I have another problem(hoping to be the last)with this program. I use this :

string val = "36";
            //string semnalv = "Umiditate";
private void button1_Click(object sender, EventArgs e)
        {
            System.Xml.XmlDocument docxml = new System.Xml.XmlDocument();
            docxml.Load(@"licenta2.xml");
            System.Xml.XmlElement root= docxml.DocumentElement;
            System.Xml.XmlElement conditie = (System.Xml.XmlElement)root.ChildNodes[0].ChildNodes[0];
       //     string semnal = conditie.ChildNodes[0].InnerText;
            string operator_semnal = conditie.ChildNodes[1].InnerText;
            string valoare = conditie.ChildNodes[2].InnerText;
            string op = root.ChildNodes[0].ChildNodes[1].InnerText; ;

            if (conditie.ChildNodes[0].InnerText.Equals("Umiditate"))
            {
                if (operator_semnal.Equals("="))
                {
                    int res = val.CompareTo(valoare);
                    if (res == 0)
                        MessageBox.Show("valorile sunt egale(umiditate)");
                    else if (res < 0)
                        MessageBox.Show("valoarea de la senzor este mai mica(umiditate)");
                    else
                        MessageBox.Show("valoarea de la senzor este mai mare(umiditate)");
                    //MessageBox.Show("bun");

                }
            }
            if (conditie.ChildNodes[0].InnerText.Equals("Temperatura"))
            {
                if (operator_semnal.Equals(">"))
                {
                    int res = val.CompareTo(valoare);
                    if (res == 0)
                        MessageBox.Show("valorile sunt egale(temp)");
                    else if (res < 0)
                        MessageBox.Show("valoarea de la senzor este mai mica(temp)");
                    else
                        MessageBox.Show("valoarea de la senzor este mai mare(temp)");

I want my program to check all childs and it seems i's stuck at the first one("Umiditate") and doesn't check the other(Temperatura). How do i check all the nodes and show messaje apropriately? Thank you.

You may use getElementsByTagName() method to get the list of specific nodes.

e.g.

NodeList nList=doc.DocumentElement.getElementsByTagName("yourTagName");
 ....

The thing is that i don't know what the nodes will be and what values will have baut i know the xml structure and that is like the one on top of the thread. For example i put a condition and it checks for the first node and its elements. I just want that condition to go to the next node and check it too after it's done with the first node(even if at the first node doesn't find anything, maybe it'll find on the second or on the third..).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.