簡體   English   中英

解析自定義.net中的xml

[英]Parsing customized xml in .net

我有一個 xml 字符串,當我想解析這個 xml 時,我真的做不到,因為這個 xml 的結構不清楚,,,

下面是我的 xml 字符串...

<?xml version="1.0" encoding="UTF-8"?> 
<test1> 
<test2>  
<test3 name="responseCode" value="xxxxx" />  
<test3 name="responseDescription" xxxxxx" />  
</test2>  
</test1>

我真的想要這個 xml 代碼的 c# 解析器,,

誰能幫我? 謝謝

我不知道你從哪里得到你的 XML 但這一行......

<test3 name="responseDescription" xxxxxx" />

... 被打破。 這為我解析...

 <test3 name="responseDescription xxxxxx" />

整個示例有效...

var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \r\n<test1> \r\n<test2>  \r\n<test3 name=\"responseCode\" value=\"xxxxx\" />  \r\n<test3 name=\"responseDescription xxxxxx\" />  \r\n</test2>  \r\n</test1>";

var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);

首先我想說你的 xml 字符串不是標准格式,你需要編寫你的自定義解析器,正如我看到你的 xml 字符串,可以解析你的字符串的代碼如下所示:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(resulStr); // Load the XML document from the specified file
XmlNodeList response = xmlDoc.GetElementsByTagName("test1");


foreach (XmlNode xn in response)
{
    XmlNodeList records = xn.SelectNodes("test2");
    foreach (XmlNode record in records)
    {
        if (record != null)
        {
            for (int i = 0; i < record.ChildNodes.Count; i++)
            {
                var objfield = record.ChildNodes.Item(i).OuterXml;
                var attributes = Utility.GetSrcInHTMLImgString(objfield);
                var attrkey = attributes[1];
                var attrvalue = attributes[0];
                
            }
        }
    }
    
}

以及用於解析每個 test3 字段的 GetSrcInHTMLImgString 函數(我為每個 test3 字段使用 html 解析器),下面的代碼是根據您的 xml 字符串的 htl 解析器:

public static List<string> GetSrcInHTMLImgString(string htmlString)
        {
            List<string> srcs = new List<string>();
            string pattern1 = @"(?<=value="").*?(?="")";
            string pattern2 = @"(?<=name="").*?(?="")";
            Regex rgx1 = new Regex(pattern1, RegexOptions.IgnoreCase);
            Regex rgx2 = new Regex(pattern2, RegexOptions.IgnoreCase);
            MatchCollection matches1 = rgx1.Matches(htmlString);
            MatchCollection matches2 = rgx2.Matches(htmlString);
            string value1 = matches1[0].Value;
            string value2 = matches2[0].Value;
            srcs.Add(value1);
            srcs.Add(value2);
            
            return srcs;
        }

我想如果你使用這些代碼你的問題就解決了,最好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM