简体   繁体   English

C#如何从简单的XML模式获取XML标签值

[英]c# how to get XML tag values from a simple XML schema

I have a XML that I get from other application that its structure is like this: 我从其他应用程序获得的XML的结构如下:

<uid>1DE23B0B-1601-4E48-B8F5-7D3152A815A1</uid>
<status>1</status>

Is there a way how can I get the values without using XMLDocument , actually I even don't know if XMLDocument can load a XML with these simple schema. 有没有一种方法可以在使用XMLDocument 情况下获取值,实际上我什至不知道XMLDocument可以使用这些简单模式加载XML。

Any clue? 有什么线索吗?

Since your xml is not well-formed (has multiple roots) - you can't load it into XmlDocument or XDocument - you will get parsing error. 由于您的xml格式不正确(具有多个根),无法将其加载到XmlDocumentXDocument ,因此会出现解析错误。

However, you can read it for example, with XMLTextReader if you'll specify ConformanceLevel.Fragment in its settings: 但是,如果要在其设置中指定ConformanceLevel.Fragment ,则可以使用XMLTextReader进行读取:

var settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
var reader = XmlReader.Create(@"c:\temp\test.xml", settings);
while (reader.Read())
{
    if (reader.NodeType == XmlNodeType.Element)
    {
        var nodeName = reader.Name;
        reader.Read();
        var value = reader.Value;
    }
}

You can parse your pseudo-xml via regex like this: 您可以通过regex解析伪XML,如下所示:

internal class Data
{
    public string UId { get; set; }
    public string Status { get; set; }

    public Data(string text)
    {
        string strRegex = @"<uid>(.*?)</uid>.*?<status>(.*?)</status>";
        Regex myRegex = new Regex(strRegex, RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);

        var match = myRegex.Match(text);
        UId = match.Groups[1].Value;
        Status = match.Groups[2].Value;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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