1

I am new to this area. Please let me know that how can i get or display

bookstore, book, title, price (DISTINCT Output i needed)

From the following XML file, how can i read and print DISTINCT xml nodes.

<?xml version="1.0" encoding="UTF-8"?>

<bookstore>
  <book>
    <title lang="en">Harry Potter</title>
    <price>29.99</price>
  </book>

  <book>
    <title lang="en">Learning XML</title>
    <price>39.95</price>
  </book>
</bookstore>

2 Answers 2

2

It's easy to do with Linq to XML:

var xdoc = XDocument.Load(fileName);
var names = xdoc.Descendants() // get all elements from xml
                .Select(e => e.Name.LocalName) // select local name of each element
                .Distinct(); // pick only distinct names

For your sample xml output is

[
  "bookstore",
  "book",
  "title",
  "price"
]

Descendants() is same as XPathSelectElements("//*")

Sign up to request clarification or add additional context in comments.

2 Comments

@NithinPaul they named differently, so they are not same :) Follow the link and read quick introduction to LINQ for xml. And yes, you need using System.Xml.Linq and using System.Linq for projection and distinct call.
@Sergery yes i found it. Thanks its working great. :)
1

try this

    public void Load()
{
    var doc = XDocument.Load(filePath);

    foreach(var unit in doc.Descendants("Unit"))
    {
        string str = string.Format("ID: {0}\r\nName:{0}", unit.Element("id").Value, unit.Element("name").Value);
        MessageBox.Show(str);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.