0

I'm currently looking for a way to read attributes from multiple XElements into an array, but I couldn't figure out how. My XML file looks like this:

<transaction date="02.11.2018" product="product1" price="0,1$" amount="1" profit="0,1$" />
<transaction date="02.11.2018" product="product2" price="1$" amount="1" profit="1€" />
<transaction date="02.11.2018" product="product1" price="1$" amount="3" profit="3$" />
Al Fahad
  • 2,378
  • 5
  • 28
  • 37
  • Is there any reason you have "one element per line" rather than a genuine XML document? – Jon Skeet Nov 02 '18 at 16:52
  • It's also not clear what you mean by "read attributes from multiple XElements into an array" - what would you expect the output to be? The question isn't clear enough to answer at the moment, IMO. – Jon Skeet Nov 02 '18 at 16:54
  • Agreeing that this is not a valid XML document. – dbasnett Nov 08 '18 at 14:45

1 Answers1

-2

Make then KeyValuePair

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

namespace ConsoleApplication75
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            var results = doc.Descendants("transaction").Select(x => x.Attributes().Select(y => new KeyValuePair<string, string>(y.Name.LocalName, y.Value)).ToArray()).ToArray();

        }


    }


}
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • The OP appears not to have a valid XML document, but instead a file containing three lines, each of which is a separate element. – Jon Skeet Nov 02 '18 at 16:52
  • It doesn't matter. My code uses Descendant to get data. I added a Root when testing. OPs do not know enough to post correct amount of data. People give negative points for too much data and tool little data. The answer should not be rated on OPs lack of knowledge. – jdweng Nov 02 '18 at 17:54
  • 1
    You're *assuming* the OP has a genuine XML document. It absolutely matters if they don't. I also don't think the OP has given enough information about how they want the attributes to be represented. I don't think it's a good idea to answer a question which is basically too unclear. (Does the OP actually want `KeyValuePair` elements? Might they be fine with just the `XAttribute` instances themselves? There's nothing in the question to say otherwise...) – Jon Skeet Nov 02 '18 at 18:05
  • So my answer could be that exact answer the person wants but I'm given negative points. If the person want a modification to my code it is very easy to do. – jdweng Nov 02 '18 at 20:24
  • I maintain it's not a useful answer in its current form, and that a decent answer really isn't feasible with the question in *its* current form. You can disagree with me, of course - but I doubt that either of us will convince the other. – Jon Skeet Nov 02 '18 at 21:53