我试图让我的函数输出xml,但函数不断返回null值。我尝试调试字符串a 和字符串b 。
String a = Illiquidity option, credit model minted, Pricing service unveiled
String b = <p>…</p>, <p>…</p>, <p>…</p>
请告诉我可能出错的地方。谢谢。
public string articleXMLTest()
{
string a = testtitle();
string b = testStory();
string c = "";
string results = "";
string[] aA = a.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string[] bA = b.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (aA.Length == bA.Length)
{
for (int i = 0; i < aA.Length; i++)
{
DateTime dt = DateTime.Today;
XDocument doc = new XDocument(
new XDeclaration("1.0", "gb2312", string.Empty),
new XElement("article",
new XElement("status", "Approved"),
new XElement("title", aA[i].ToString()),
new XElement("subtitle", aA[i].ToString()),
new XElement("synopsis", bA[i].ToString() + "..."),
new XElement("url", c),
new XElement("display_date", dt.ToShortDateString())
));
results = results + Environment.NewLine + doc.ToString();
}
}
return results;
}
答案 0 :(得分:2)
这对我来说没问题。由于此代码正常工作,我可以想象的唯一可能性是返回位于if
之外,如果您的长度匹配,则会返回null
。
以这种方式再次检查输出:
public string articleXMLTest()
{
string a = testtitle();
string b = testStory();
string c = "";
string results = "";
// Debug the length of your arrays. Im pretty sure they wont match.
string[] aA = a.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
string[] bA = b.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (aA.Length == bA.Length)
{
for (int i = 0; i < aA.Length; i++)
{
DateTime dt = DateTime.Today;
XDocument doc = new XDocument(
new XDeclaration("1.0", "gb2312", string.Empty),
new XElement("article",
new XElement("status", "Approved"),
new XElement("title", aA[i].ToString()),
new XElement("subtitle", aA[i].ToString()),
new XElement("synopsis", bA[i].ToString() + "..."),
new XElement("url", c),
new XElement("display_date", dt.ToShortDateString())
));
results = results + Environment.NewLine + doc.ToString();
}
// Or set a breakpoint here to check if it reaches this return.
return results;
}
// I guess you will end up here.
return "Length of aA isnt matching length of bA";
}
<强>问题:强>
String b = <p>…</p>, <p>…</p>, <p>…</p>
您的...
部分也会有一些逗号。
<强>解决方案:强>
对于b
,请使用此分割:
Regex rgxPTag = new Regex("<p>(.*?)<\\/p>");
string[] bA = rgxPTag.Matches(test).Cast<Match>().Select(m => m.Groups[1].Value).ToArray();
如果您还需要<p>
标签:
Regex rgxPTag = new Regex("(<p>.*?<\\/p>)");
string[] bA = rgxPTag.Matches(test).Cast<Match>().Select(m => m.Groups[1].Value).ToArray();
<强>注意:强>
如果<p>
和</p>
之间存在换行符,则需要定义SingleLineMode
才能使正则表达式生效:
Regex rgxPTag = new Regex("...", RegexOptions.Singleline);
答案 1 :(得分:0)
我测试了它确实有效的代码。也许会出现任何你不能处理的异常。
E.g。数组aA
和bA
的长度不同。