How to Read a specific element value from XElement in LINQ to XML

前端 未结 3 1096
感情败类
感情败类 2021-01-12 09:31

I have an XElement which has content like this.


   
         


        
相关标签:
3条回答
  • 2021-01-12 09:52
    XElement response = XElement.Load("file.xml"); // XElement.Parse(stringWithXmlGoesHere)
    XNamespace df = response.Name.Namespace;
    XElement status = response.Element(df + "Status");
    

    should suffice to access the Status child element. If you want the value of that element as a string then do e.g.

    string status = (string)response.Element(df + "Status");
    
    0 讨论(0)
  • 2021-01-12 09:52

    If myXel already is the Response XElement then it would be:

    var status = myXel.Elements().Where(e => e.Name.LocalName == "Status").Single().Value;
    

    You need to use the LocalName to ignore namespaces.

    0 讨论(0)
  • 2021-01-12 10:00

    Some TextReaders know that there will be more data soon, but that not all characters are available right now. If you ask for 10 characters, and there are now only 4 characters available, but the other ones will become available in a few seconds, then it might be wiser to return the 4 available characters instead of waiting for all 10 characters.

    An example could be a TextReader that bufferst data from a serial port: it would be too slow to wait until all requested characters are available, hence it will return all characters that are already available right now.

    You can see the difference between TextReader.Read(char[], int, int) and TextReader.ReadBlock(char[], int, int) at the description of the return value:

    TextReader.Read

    Returns: The number of characters that have been read, or 0 if at the end of the stream and no data was read. The number will be less than or equal to the count parameter, depending on whether the data is available within the stream.

    TextReader.ReadBlock

    Returns: The number of characters that have been read. The number will be less than or equal to count, depending on whether all input characters have been read.

    If you ask a TextReader to Read 10 characters, Read is allowed to return with less than 10 characters if the reader thinks that it is not wise to wait for all 10 characters. As long as the reader knows that there are still characters, it will wait for at least one character. If Read returns that 4 bytes are read, then you don't know if the last character has been read. Only if Read returns zero you know there is nothing to read anymore. This allows the TextReader to return the characters that are available right now without having to wait for all 10 characters to become available.

    ReadBlock would wait until all 10 bytes become available (or EOF). So a slow reader might block your process longer than you desire.

    To be certain that you've read all characters, Use 'Readrepeatedly until you get a zero return; UseReadBlock` repeatedly until you read less bytes than requested.

    0 讨论(0)
提交回复
热议问题