我的xml文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<roulette xmlns="Mechanical" name="Ruleta">
<params name="Mechanical Counters">
<param name="C01">
<comm>30313</comm>
<command>INA</command>
<factor>5</factor>
<index>2</index>
<meter>0</meter>
<player>1023</player>
<meterstring>ml_BET</meterstring>
</param>
<param name="C02">
<comm>30313</comm>
<command>INC</command>
<factor>5</factor>
<index>3</index>
<meter>0</meter>
<player>1023</player>
<meterstring>ml_WIN_PAYTABLE</meterstring>
</param>
<param name="C03">
<comm>30313</comm>
<command>INE</command>
<factor>5</factor>
<index>0</index>
<meter>0</meter>
<player>1023</player>
<meterstring>ml_CRE_IN_BA + ml_CRE_IN_REM + ml_CRE_IN_KEY + ml_CRE_IN_TICKET</meterstring>
</param>
<param name="C04">
<comm>30313</comm>
<command>ING</command>
<factor>5</factor>
<index>1</index>
<meter>0</meter>
<player>1023</player>
<meterstring>ml_CRE_OUT_KEY + ml_CRE_OUT_HANDPAY + ml_CRE_OUT_HANDPAYJP + ml_CRE_OUT_REM + ml_CRE_OUT_TICKET</meterstring>
</param>
<param name="Percentage">
<factor>10</factor>
</param>
<param name="WaitAnswer">
<miliseconds>2500</miliseconds>
</param>
</params>
</roulette>
我正在尝试解析其中name {1}}元素的comm
元素,其中name等于C01,以便在文本框中显示它。
我的代码如下所示:
param
问题是它没有解析任何东西(var private void radioButton1_Click(object sender, EventArgs e)
{
//loadamo xml dokument
var doc = XDocument.Load("mechanical.xml");
//preberemo prvi element števca C01 comm
var prvi = doc.Descendants("param")
.Where(x => (string)x.Attribute("name") == "C01")
.Elements("comm")
.FirstOrDefault();
if (prvi != null) { textBox1.Text = "Je element"; } else { textBox1.Text = "ni elementa"; }
}
为null)但它不应该代码。问题是什么?
答案 0 :(得分:3)
您的xml有一个默认的命名空间xmlns="Mechanical"
。要访问元素,您必须指定命名空间。
XNamespace ns = "Mechanical";
var prvi = doc.Descendants(ns + "param")
.Where(x => (string)x.Attribute("name") == "C01")
.Elements(ns + "comm")
.FirstOrDefault();
请注意,默认名称空间不直接应用于属性。
有关详细信息,请参阅Namespace Defaulting。