简体   繁体   中英

Get datas from XML document

I would like to get datas from a specific XML format. The XML document looks like that:

<MyXML>
<Sources> 
     <S1>www.example1.org</S1>
     <S2>www.example2.org</S2>
</Sources>
<Books>
    <Book id="1">
        <Datas>
            <Data name="Book_1_Name" tag="1111" />
            <Data name="Book_2_Name" tag="2222" />
        </Datas>
    </Book >
    <Book id="2">
        <Datas>
            <Data name="Book_1_Name" tag="3333" />
            <Data name="Book_2_Name" tag="4444" />
        </Datas>
    </Book >
</Books>

My question is: How can I get www.example1.org if I know S1? How can I search " Book_1_name " from Book id=1?

I am using C# with XDocument like this:

XDocument.Load(_XML_path);
var node = _configXml.XPathSelectElement("MyXML/Books/Datas");

You should map the XML to a C# object. Then, you can use the following to get what you want:

XmlSerializer serializer = new XmlSerializer(typeof(MyXML));
var xml = (MyXML)serializer.Deserialize(new StringReader(XDocument.Load(_XML_path)));
var s1 = xml.Sources.S1;

You can use XPath , About XPath see this : http://www.xfront.com/xpath/

var _configXml = XDocument.Load(_XML_path);
//how to get S1 element.
var s1 = _configXml.XPathSelectElement("MyXML/Sources/S1");
//how search
var search = _configXml.XPathSelectElements("//Book[@id='1']//Data[@name='Book_1_Name']");
Console.WriteLine(s1.Value);
Console.WriteLine(search.First().Attribute("tag").Value);

If you want to stick with a XDocument , you can do the following

var books = doc.Element("MyXML").Element("Books");
var bookById = books.Elements("Book")
                    .Where(b => b.Attribute("id").Value == "1")
                    .Select(b => b.Element("Datas"));

In the first line, you are selecting the Books node (please note, in a real-world scenario, I'd add some checks here). In the following line you are first getting all Book sub-elements ( books.Elements("Book") ), checking them for the ID you are searching for ( Where(b => b.Attribute("id").Value == "1") ) and then select the data node from the respective book. You could re-write this to query syntax

var bookById = from book in books.Elements("Book")
               let id = book.Attribute("id")
               let datas = book.Element("Datas")
               where id != null
                    && datas != null
                    && id.Value == "1"
               select datas;

which is a bit longer, but easier to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM