Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用&;书信电报;及;燃气轮机;_C#_Xml_Regex - Fatal编程技术网

C# 使用&;书信电报;及;燃气轮机;

C# 使用&;书信电报;及;燃气轮机;,c#,xml,regex,C#,Xml,Regex,我试图剥离一些XML,只获取与字段相关的值,但是XML不使用小于和大于符号。我尝试在字段名周围加上子字符串(在下面的例子中是Date),这样做很好 <my:Date xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2014-07-27T23:04:34">2014-08-15</my:Date> 但是,我无法在小于和大于之间进行子串。我的代码如下:

我试图剥离一些XML,只获取与字段相关的值,但是XML不使用小于和大于符号。我尝试在字段名周围加上子字符串(在下面的例子中是Date),这样做很好

    <my:Date xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2014-07-27T23:04:34">2014-08-15</my:Date>
但是,我无法在小于和大于之间进行子串。我的代码如下:

public string processReportXML(string field, string xml)
    {
        try
        {
            string result = xml.Substring(xml.IndexOf(field));
            int resultIndex = result.LastIndexOf(field);
            if (resultIndex != -1) result = result.Substring(0, resultIndex);

            result = result.Substring(result.IndexOf(">"));
            resultIndex = result.IndexOf("<");
            if (resultIndex != -1) result = result.Substring(0, resultIndex);

            return field + ": " + result.Substring(4) + "\n";
        }
        catch (Exception e)
        {
            return field + " failed\n";
        }
    }
我在一个测试项目中进行了尝试,效果很好,但在我的实际web服务中,我总是得到索引应该大于0的结果。我也尝试过用正则表达式替换字符,但这也不起作用

result = Regex.Replace(result, "&(?!(amp|apos|quot|lt|gt);)", "hidoesthiswork?");

您有HTML编码的数据

在方法的开头添加以下内容,以获得简单的解决方案:

xml = HttpUtility.HtmlDecode(xml);
如果在中使用.NET 4.0+,也可以使用
WebUtility.HtmlDecode


从长远来看,您应该真正使用XML解析器或类似LINQ-XML的东西来访问这些数据。ReGEXES不是这种结构化数据的合适工具。

谢谢:现在我应该能够在标签之间获取内文了,对吗?是的,你确实应该考虑使用LINQ到XML来做这件事:不过,好吧,我会添加一个根节点来形成它,对吧?然后循环遍历HTML并使每个元素成为一个新的XElement?您不需要循环,只需通过LINQ-SQL将其转换为一个集合即可。好好读一读,很酷!