Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

c# - XML parser, multiple roots

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

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

1 Reply

0 votes
by (71.8m points)

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
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...