如何从包含冒号的XML元素中获取值

时间:2015-07-29 15:54:53

标签: c# xml linq

为了实现上述目的,我尝试了各种XNamespace变体。最后,我需要字符串中POSITION属性的值,并带有分隔符:" 1 | 2 | 3 | 4"

代码:

XNamespace z = "z";
XNamespace rs = "rs";
var doc = XDocument.Parse(returnValue);
IEnumerable<XElement> list = doc.Root.Descendants(rs +"data");

foreach (var item in list) 
{
    returnValue += item.Element(z + "row").Attribute("POSITION").Value;
    returnValue += "|";
}

XML:

<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://schemas/Order">
  <span id="TData">
    <xml pagingEnabled="false" allDataMode="false" rowCount="4">
      <s:Schema xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" id="RowsetSchema">
        <s:ElementType name="row" content="eltOnly">
          <s:AttributeType name="POSITION">
            <s:datatype dt:type="i4" rs:maybenull="false"/>
          </s:AttributeType>
          <s:extends type="rs:rowbase"/>
        </s:ElementType>
      </s:Schema>
      <rs:data xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema">
        <z:row POSITION="1"/>
        <z:row POSITION="2"/>
        <z:row POSITION="3"/>
        <z:row POSITION="4"/>
      </rs:data>
    </xml>
    <p>
      <form target="_self" id="pickForm" method="post"/>
    </p>
  </span>
</string>

1 个答案:

答案 0 :(得分:2)

稍微修改一下代码

XNamespace rs = "urn:schemas-microsoft-com:rowset"; //<---
XNamespace z = "#RowsetSchema"; //<---
var doc = XDocument.Parse(DATA);

IEnumerable<XElement> list = doc.Root.Descendants(rs + "data");
string returnValue = "";
foreach (var item in list.Elements(z + "row")) //<---
{
    returnValue += item.Attribute("POSITION").Value; //<---
    returnValue += "|";
}