2011-08-30 7 views
0

XML 구문 분석을하고 있습니다. 내 xml 문서는두 개의 네임 스페이스가있는 Xml 구문 분석

<?xml version="1.0"?> 
<BCPFORMAT 
xmlns="http://schemas.microsoft.com/sqlserver/2004/bulkload/format" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <RECORD> 
    <FIELD ID="1" xsi:type="CharTerm" TERMINATOR="\t" 
     MAX_LENGTH="12"/> 
    <FIELD ID="2" xsi:type="CharTerm" TERMINATOR="\t" 
     MAX_LENGTH="20" COLLATION="SQL_Latin1_General_CP1_CI_AS"/> 
    <FIELD ID="3" xsi:type="CharTerm" TERMINATOR="\r\n" 
     MAX_LENGTH="30" 
     COLLATION="SQL_Latin1_General_CP1_CI_AS"/> 
    </RECORD> 
    <ROW> 
    <COLUMN SOURCE="1" NAME="age" xsi:type="SQLINT"/> 
    <COLUMN SOURCE="2" NAME="firstname" xsi:type="SQLVARYCHAR"/> 
    <COLUMN SOURCE="3" NAME="lastname" xsi:type="SQLVARYCHAR"/> 
    </ROW> 
</BCPFORMAT> 

이 문서를 파싱하는 데 도움을주십시오.

+0

그냥 XmlDocument 또는 XDocument를 사용하십시오. –

+1

에 무엇을 파싱 하시겠습니까? 당신의 결과물은 무엇입니까? –

+0

위대한, 당신이 그것을 분석하고 싶다,하지만 당신이 그것을 한 후에 당신은 무엇을 할거야? XElement.Parse()를 사용하여 XElement로 변환 할 수 있습니까? – kmcc049

답변

0

이와 같이 small-ish xml 문서를 구문 분석하는 표준 방법은 XmlDocument 클래스를 사용하는 것입니다. 위의 예에서 우리는 요소의 네임 스페이스를 지정하는 XmlNamespaceManager를 사용하는 데 필요한 것을

XmlDocument doc = new XmlDocument(); 
doc.Load("test.xml"); 

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); 
nsmgr.AddNamespace("bulk", "http://schemas.microsoft.com/sqlserver/2004/bulkload/format"); 

XmlElement fieldElement = (XmlElement)doc.SelectSingleNode("bulk:BCPFORMAT/bulk:RECORD/bulk:FIELD[@ID = 1]", nsmgr); 
Console.WriteLine(fieldElement.Attributes["MAX_LENGTH"].Value); 

참고 : XML 문서가 파일에 포함되어있는 경우, 시작할 수 있도록 "test.xml의는"다음을 사용할 수 있습니다 우리의 xpath 표현식에서. HOW TO: Specify Namespaces When You Use an XmlDocument to Execute XPath Queries in Visual C# .NET

자세한 내용은 xpath 및 XmlDocument 클래스의 여러 자습서 중 하나를 사용해야합니다.

완전성을 위해 여기에 XDocument 클래스를 사용하는 동일한 예제가 있습니다. 이 기능을 사용하려면 using System.Xml.XPath;을 사용해야합니다.

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

XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); 
nsmgr.AddNamespace("bulk", "http://schemas.microsoft.com/sqlserver/2004/bulkload/format"); 

XElement fieldElement = (XElement)doc.XPathSelectElement("bulk:BCPFORMAT/bulk:RECORD/bulk:FIELD[@ID = 1]", nsmgr); 
Console.WriteLine(fieldElement.Attribute(XName.Get("MAX_LENGTH")).Value); 
+0

OP는 거의 확실하게 __XDocument__ 클래스를 사용하려고합니다. XmlDocument는 약간 날짜가 오래되어 사용하기가 더 어렵습니다. –

+0

@Henk * really *? 기껏해야'XDocument '의 사용법은 거의 동일합니다. 만약 파손되지 않았다면 ... – Justin

+1

브리징 XPath 방법을 사용하는 경우에만 사용법이 동일합니다. 더 많은 네이티브 .Elements, .Attribute, .Descendents 등을 사용하면 다른 것이됩니다. –

관련 문제