Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

This is part of the input string, i can't modify it, it will always come in this way(via shared memory), but i can modify after i have put it into a string of course:

<sys><id>SCPUCLK</id><label>CPU Clock</label><value>2930</value></sys><sys><id>SCPUMUL</id><label>CPU Multiplier</label><value>11.0</value></sys><sys><id>SCPUFSB</id><label>CPU FSB</label><value>266</value></sys>

i've read it with both:

        String.Concat(
            XElement.Parse(encoding.GetString(bytes))
                .Descendants("value")
                .Select(v => v.Value));

and:

    XmlDocument document = new XmlDocument();
    document.LoadXml(encoding.GetString(bytes));
    XmlNode node = document.DocumentElement.SelectSingleNode("//value");
    Console.WriteLine("node = " + node);

but they both have an error when run; that the input has multiple roots(There are multiple root elements quote), i don't want to have to split the string.

Is their any way to read the string take the value between <value> and </value> without spiting the string into multiple inputs?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
160 views
Welcome To Ask or Share your Answers For Others

1 Answer

That's not a well-formed XML document, so most XML tools won't be able to process it.

An exception is the XmlReader. Look up XmlReaderSettings.ConformanceLevel in MSDN. If you set it to ConformanceLevel.Fragment, you can create an XmlReader with those settings and use it to read elements from a stream that has no top-level element.

You have to write code that uses XmlReader.Read() to do this - you can't just feed it to an XmlDocument (which does require that there be a single top-level element).

e.g.,

var readerSettings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
using (var reader = XmlReader.Create(stream, readerSettings))
{
    while (reader.Read())
    {
        using (var fragmentReader = reader.ReadSubtree())
        {
            if (fragmentReader.Read())
            {
                var fragment = XNode.ReadFrom(fragmentReader) as XElement;

                // do something with fragment
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...