0

Below is my XML file. I want to get the node "name" from the XML using C#

'EventObjectsRead' ('73')
message attributes:
SATRCFG_OBJECT [xml] = 
<ConfData>
  <CfgAgentGroup>
    <CfgGroup>
      <DBID value="225"/>
      <tenantDBID value="101"/>
      <name value="CBD"/>
      <routeDNDBIDs>
        <DBID value="825"/>
      </routeDNDBIDs>
      <capacityTableDBID value="0"/>
      <quotaTableDBID value="0"/>
      <state value="1"/>
      <capacityRuleDBID value="0"/>
      <siteDBID value="0"/>
      <contractDBID value="0"/>
    </CfgGroup>
    <agentDBIDs>
      <DBID value="128"/>
      <DBID value="133"/>
      <DBID value="135"/>
      <DBID value="385"/>
      <DBID value="433"/>
    </agentDBIDs>
  </CfgAgentGroup>
</ConfData>

IATRCFG_TOTALCOUNT [int] = 1
IATRCFG_OBJECTCOUNT [int] = 1
IATRCFG_OBJECTTYPE [int] = 5
IATRCFG_REQUESTID [int] = 3

Is there a way to get node "name" directly from above XML or if i need to trim first three lines and last four lines. how can i do it.

Marco
  • 22,856
  • 9
  • 75
  • 124

3 Answers3

0

You could extract the node you are looking for using Regex on the original string (where str is your string data):

// Use Regex to match the exact string and parse that to XElement.
string nameXML = Regex.Match(str, @"<name +value="".*"" */>").Groups[0].Value;
XElement name = XElement.Parse(nameXML);

Or here is an example where you can strip the invalid lines, parse the XML and then access the data from an XML object:

// Split the string into groups using newline as a delimiter.
string[] groups = str.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
// Use skip and take to trim the first 3 and last 4 elements.
// Rejoin the remainder back together with empty strings and parse the XElement.
string xmlString = string.Join(string.Empty, groups.Take(groups.Length - 4).Skip(3));
XElement xml = XElement.Parse(xmlString);
// Use Descendants and First to get the first node called 'name' in the XML.
XElement name = xml.Descendants("name").First();
TVOHM
  • 2,740
  • 1
  • 19
  • 29
-1

Here are two ways to achieve this. Either with string operation or with RegEx:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Name: {0}", GetNameFromFileString(File.ReadAllText("file.txt")));
        Console.WriteLine("Name: {0}", GetNameFromFile("file.txt"));
    }

    private static string GetNameFromFileString(string filecontent)
    {
        Regex r = new Regex("(?<Xml><ConfData>.*</ConfData>)", RegexOptions.Singleline);
        var match = r.Match(filecontent);
        var xmlString = match.Groups["Xml"].ToString();
        return GetNameFromXmlString(xmlString);
    }

    private static string GetNameFromFile(string filename)
    {
        var lines = File.ReadAllLines(filename);
        var xml = new StringBuilder();
        var isXml = false;
        foreach (var line in lines)
        {
            if (line.Contains("<ConfData>"))
                isXml = true;
            if (isXml)
                xml.Append(line.Trim());
            if (line.Contains("</ConfData>"))
                isXml = false;
        }

        var text = xml.ToString();
        return GetNameFromXmlString(text);
    }

    private static string GetNameFromXmlString(string text)
    {
        var xDocument = XDocument.Parse(text);
        var cfgAgentGroupt = xDocument.Root.Element("CfgAgentGroup");
        var cfgGroup = cfgAgentGroupt.Element("CfgGroup");
        var name = cfgGroup.Element("name");
        var nameValue = name.Attribute("value");
        var value = nameValue.Value;
        return value;
    }
}
Matt
  • 4,612
  • 1
  • 24
  • 44
  • @StenPetrov Well, what do you mean. – Matt Jan 28 '16 at 19:59
  • the code is way too big compared to the complexity of the problem. – Sten Petrov Jan 28 '16 at 22:27
  • @StenPetrov This is just another way to tell this again. Sure it could be shorter than 11 lines, but regarding his rep I answered a bit longer than necessary. But of course I'm looking forward to your answer. – Matt Jan 28 '16 at 22:41
  • This code throws an exception when a new line is added in the xml. (). Above code throws error un handled exception (DevLab_DLG_CM"). When i am trying to fetch name details from each node CfgGroup. Below is the XML which results in exception:- – user3355488 Jan 30 '16 at 05:58
-2

From the string what you provided us and the describtion of what you want to do i assume taht you want to extract the XMl from the file. I would do this in the following way:

        string text = System.IO.File.ReadAllText(@"C:\docs\myfile.txt");
        Regex r = new Regex("<ConfData>(.|\r\n)*?</ConfData>");
        var v = r.Match(text);

        string myResult = "<ConfData>" + v.Groups[0].ToString() + "</ConfData>";
STORM
  • 4,005
  • 11
  • 49
  • 98
  • @Serv: Why not? When you remove the first two line and the last four lines, you extract the XML from the file. – STORM Jan 28 '16 at 19:02
  • Then incorporate this into your answer, would you? – Marco Jan 28 '16 at 19:05
  • @Serv can you explain? OP wants the XML and has obviously stated their question incorrectly, it should be "how do I get the XML out of this mess" – Sten Petrov Jan 28 '16 at 19:34