开发者

How to extract XML data

I have a XML file that has the following data,

<extcode Type="abc" Code="12345" />

I want to be able to extract the Code, i.e., 12345, for rows where Type is abc. I t开发者_StackOverflowried

XPathSelectElements("Type[@name='abc']")

but it returned nothing.

Thanks.

Edit I figured out that the problem is with namespace. The XML file is like aw:extcode instead of just extcode and that caused the query to not work properly. How should I do it in the presence of namespace? When I tried to use

XmlNameTable nameTable = doc.NameTable;

compiler complains that it can't resolve NameTable.


Use this XPath: //extcode[@Type = 'abc']/@Code


Personally I'd use LINQ to XML, as my preferred way of working with XML data. Something like this:

XDocument doc = XDocument.Load("test.xml");

int code = doc.Descendants("extCode")
              .Where(x => (string) x.Attribute("Type") == "abc")
              .First()
              .Attribute("Code");

One reason why your XPath isn't working may be that the attribute is called "Type" rather than "name" though...


you can write like this ↓

        XDocument doc = XDocument.Load("test.xml");
        var x = doc.Root.XPathSelectElement("./extcode[@Type='abc']");
        Console.WriteLine("x:" + x.ToString());


XDocument xmlDoc = XDocument.Load(Server.MapPath("~/FolderName/FileName.xml"));

var output= from obj in xmlDoc.Element("extcode")
            where obj.Attribute("Type").Value.ToLower() == "abc"
            select obj;

DataTable outputTable = new DataTable();
outputTable.Columns.Add(new DataColumn("code"));

foreach (var item in output)
{
   DataRow outputRows = outputTable.NewRow();

   if (outputRows != null)
   {
      outputRows["Code"] = item.Element("code").Value;
   }
}
outputTable.Rows.Add(problemsRows);
outputTable.AcceptChanges();

now we have output data table you can use the data where ever you need .


Edit I figured out that the problem is with namespace. The XML file is like aw:extcode instead of just extcode and that caused the query to not work properly. How should I do it in the presence of namespace?

Writing an XPath expression to be applied on an XML document with namespaces is one of the most FAQ about XPath.

Use the XmlNode.SelectNodes() overload that has an XmlNamespaceManager as its second argument.

The first linked-to page has a complete code example suitable for your case.

Alternative ways are to use XPathNavigator.Evaluate() or XPathNavigator.Select() overloads that use as their second argument IXmlNamespaceResolver.

With LINQ you can use the Extensions.XPathEvaluate() method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜