[英]How to get XML nodes InnerText without concatenation and using Xml.Linq in C#?
I already checked several questions posted at Stackoverflow but seems that none of them can solve my situation which i can try to explain.我已经检查了 Stackoverflow 上发布的几个问题,但似乎没有一个可以解决我可以尝试解释的情况。
I have next XML file into disk ( commands.xml
) with following contents:我将下一个 XML 文件放入磁盘(
commands.xml
),内容如下:
<?xml version="1.0" encoding="utf-8"?>
<categories>
<category name="Standard">
<cmd name="pwd">
<description>Get working dir.</description>
<code>echo getcwd();</code>
</cmd>
<cmd name="cat">
<description>Reads a file.</description>
<code>$fh = fopen("<<cmd>>", 'r') or die ("Cant open file");
$lines = fread($fh, filesize("<<cmd>>"));
echo "$lines";
fclose($fh);</code>
</cmd>
</category>
</categories>
I'm trying to read the child-node <code>
of <cmd name="cat">
, as you can see it contains several lines.我正在尝试读取
<cmd name="cat">
的子节点<code>
<cmd name="cat">
,您可以看到它包含几行。
My actual code is:我的实际代码是:
var xml = XElement.Load("commands.xml");
var query = xml.Descendants()
.Where(x => x.Name == "category" && x.Attribute("name").Value == "Standard")
.Descendants()
.Where(x => x.Name == "cmd" && x.Attribute("name").Value == "cat");
var first_query_result = query.FirstOrDefault();
if (first_query_result != null)
{
textBox_cmd_code_editor.Text = first_query_result.Descendants("code").Single().Value;
}
The problem is that the text is concatenated and line jumps ( \\r\\n
) are stripped.问题是文本被连接并且行跳转(
\\r\\n
)被剥离。 I need to get the text as is, without any concatenation or reformatting, but don't know how to achieve it.我需要按原样获取文本,没有任何连接或重新格式化,但不知道如何实现。
I tryed multiple options but couldn't find a solution.我尝试了多种选择,但找不到解决方案。
Thanks.谢谢。
I think it may have something to do with the object you're placing the text into (the textBox_cmd_code_editor.Text).我认为这可能与您将文本放入的对象(textBox_cmd_code_editor.Text)有关。
I placed your output into a normal string variable and the newlines were preserved.我将您的输出放入一个普通的字符串变量中,并保留了换行符。
Try placing the output into a normal string variable and then manipulating it from there.尝试将输出放入一个普通的字符串变量中,然后从那里操作它。 It's likely your target object just don't support newlines, ect.
您的目标对象可能不支持换行符等。
Edit: What you need is to convert the linebreaks to Environment.NewLine, as follows:编辑:您需要的是将换行符转换为 Environment.NewLine,如下所示:
string originalString;
string convertedString;
if (first_query_result != null)
{
originalString = first_query_result.Descendants("code").Single().Value;
convertedString = Regex.Replace(originalString, @"\r\n?|\n", Environment.NewLine);
textBox1.Text = convertedString;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.