2014-02-14 4 views
1

의 XML 노드 설명에있는 값을 추출합니다. XML 태그 내부의 텍스트를 구문 분석하고 추출 할 수 있습니다. 나는 작업 태그
내 XML 파일 형식구문 분석 방법 C#

<?xml version="1.0" standalone="yes"?> 
    <SmPpProperties> 
    <SmProperties> 
     <Job Name="Job001" CreatedDate="2012-10-15T10:43:56.0972966-06:00" ModifiedDate="2012-10-  15T10:46:07.6878231-06:00"> 
//   **I am not able to extract the values present in above Job tag** 
     <NuclearSystem>Barium</NuclearSystem> 
         </Job> 
    </SmProperties> 
<SmPpProperties> 

C# 코드 노드의 값와 자식 노트 연결된

 // Load XML Document 
      XmlDocument MyDoc = new XmlDocument(); 
     // Select Node  
     MyDoc.Load(@"C:\Users\SRangarajan\Desktop\12001_.xml"); 

      XmlNode MyNode = MyDoc.SelectSingleNode("SmPpProperties/SmProperties/Job"); 
      Console.WriteLine(String.Concat("NuclearSystem: ", MyNode.InnerText)); 
      Console.ReadKey(); 

답변

0

XmlNode.InnerText 반환에 존재하는 값을 추출 할 수 없습니다입니다. 그러면 Barium이 생깁니다. Name, ModifiedDate 및 CreatedDate는 속성입니다.

귀하의 의도는 명확하지 않다,하지만 당신은 모든 속성의 연결된 값을 얻고 싶다면 :

string name = MyNode.Attributes["Name"].Value; 
string createdDate = MyNode.Attributes[1].Value; 

:

String.Join(",", MyNode.Attributes.Cast<XmlAttribute>().Select(a => a.Value)) 

을 또는 당신은 이름이나 인덱스로 특정 속성의 값을 얻을 수 있습니다 참고 : 나는 XML을 파싱하기 위해 Linq to Xml을 사용할 것을 제안한다. 당신은 쉽게 XML에서 강력한 형식의 개체를 만들 수 있습니다 : 당신의 이름에 대한 강력한 형식의 속성, 만든 날짜와 수정 날짜를해야합니다 작업 개체를 제공

var xdoc = XDocument.Load(@"C:\Users\SRangarajan\Desktop\12001_.xml"); 
XElement j = xdoc.Root.Element("SmProperties").Element("Job"); 
var job = new { 
       Name = (string)j.Attribute("Name"), 
       CreatedDate = (DateTime)j.Attribute("CreatedDate"), 
       ModifiedDate = (DateTime)j.Attribute("ModifiedDate"), 
       NuclearSystem = (string)j.Element("NuclearSystem") 
      }; 

합니다. 날짜 속성은 DateTime 유형이됩니다! 특성 속성을 사용하여 속성을 얻기 위해

string xml = "xml"; 
    XDocument xdoc = XDocument.Parse(xml); 
    XElement nuclear = xdoc.Descendants(document.Root.Name.Namespace + "NuclearSystem").FirstOrDefault(); 

    string nuclearSystem = nuclear.Value(); 
+0

를 : 이 답장을 보내 주셔서 감사합니다. string Job = node.Attributes [3] .Value; –

+0

@ShrivatsanRangarajan 네,'XmlNode.Attributes' 속성을 사용해야합니다. 색인을 기준으로 이름별로 속성을 가져올 수 있습니다. 또는 대답에 나와있는대로 모두 가져올 수 있습니다. 그리고 네,'XmlAttrubute'는 값을 반환하는 value 속성을 가지고 있습니다. –

+0

@ Sergey : 엄지 손가락 대체 솔루션. 고마워. 또한 데이터 형식 변환 fr 이러한 특성 inorder 내 SQL 데이터베이스 테이블에 삽입 할 처리 할 필요가 –

0

시도는 다음과 같이, LINQ를 사용하는 세르게이 @

XmlNode MyNode = MyDoc.SelectSingleNode("SmPpProperties/SmProperties/Job"); 
Console.WriteLine(String.Concat("Name: ", MyNode.Attributes["Name"].Value)); 
Console.WriteLine(String.Concat("CreatedDate: ", MyNode.Attributes["CreatedDate"].Value)); 
Console.WriteLine(String.Concat("ModifiedDate: ", MyNode.Attributes["ModifiedDate"].Value)); 
Console.WriteLine(String.Concat("NuclearSystem: ", MyNode.InnerText)); 
0

을 다음 값에 액세스 :

enter image description here

+0

완벽한 대답. 고마워. 나는 이것에 대한 질문을하려고했다. 답장을 보내 주셔서 감사합니다. –

+0

귀하의 환영 :) – eyalsn